Skip to content

Instantly share code, notes, and snippets.

@rpietro
Created December 29, 2013 04:23
Show Gist options
  • Save rpietro/8167429 to your computer and use it in GitHub Desktop.
Save rpietro/8167429 to your computer and use it in GitHub Desktop.
sage for calculus I, II and III
# source http://goo.gl/1zB4ee
# Calculus I
f(x)=x^3+1
f(2)
show(f)
lim(f,x=1)
lim((x^2-1)/(x-1),x=1)
lim(f,x=1,dir='-'); lim(f,x=1,dir='right'); f(1)
diff(f,x); derivative(f,x); f.derivative(x)
derivative(sinh(x^2+sqrt(x-1)),x)
P=plot(f,(x,-1,1))
P
c=1/3
fprime=derivative(f,x)
fprime
L(x)=fprime(c)*(x-c)+f(c)
Q=plot(L,(x,-1,1), color="red", linestyle="--")
P+Q
%auto # allows us to have a cell, especially an interactive one, all loaded up as soon as we start - particularly convenient for a classroom situation.
f(x)=x^3+1
@interact
def _(c=(1/3,(-1,1))):
P=plot(f,(x,-1,1))
fprime=derivative(f,x)
L(x)=fprime(c)*(x-c)+f(c)
Q=plot(L,(x,-1,1),color="red", linestyle="--")
show(P+Q+point((c,f(c)), pointsize=40, color='red'),ymin=0,ymax=2)
integral(cos(x),x)
integral(cos(x),(x,0,pi/2))
# Calculus II
h(x)=sec(x)
h.integrate(x)
integrate(sec(x),x)
integrate(1/(1+x^5),x)
integral(1/(1+x^10),x)
integral(sinh(x^2+sqrt(x-1)),x) # long execution time, if Sage doesn’t know the whole antiderivative, it returns as much of it as Maxima can do
integral(e^(-x^2),x)
erf?
integral(cos(x),(x,0,pi/2))
plot(cos(x),(x,0,pi/2),fill=True,ticks=[[0,pi/4,pi/2],None],tick_formatter=pi)
var('a,b')
integral(cos(x),(x,a,b))
integral(h,(x,0,pi/8))
N(integral(h,(x,0,pi/8)))
numerical_integral(h,0,pi/8)
numerical_integral(h,0,pi/8)[0]
ni = numerical_integral(h,0,pi/8)
ni[0]
h(x).nintegrate(x,0,pi/8)
var('n') # declare variable
sum((1/3)^n,n,0,oo)
k = var('k')
sum(binomial(n,k), k, 0, n)
g(x)=taylor(log(x),x,1,6); g(x)
plot(g,(x,0,2))+plot(log(x),(x,0,2),color='red')
# Calculus III
var('y')
f(x,y)=3*sin(x)-2*cos(y)-x*y
f.gradient(); f.hessian(); f.diff(x,y)
show(f.diff()); show(f.diff(2))
show(f.diff(2).det())
P=plot_vector_field(f.diff(), (x,-3,3), (y,-3,3))
u=vector([1,2])
Q=plot(u/u.norm())
P+Q
(f.diff()*u/u.norm())(0,0)
y = var('y')
contour_plot(y^2 + 1 - x^3 - x, (x,-pi,pi), (y,-pi,pi), contours=[-8,-4,0,4,8], colorbar=True, labels=True, label_colors='red')
integrate(integrate(f,(x,0,pi)),(y,0,pi))
plot3d(f,(x,0,pi),(y,0,pi),color='red')+plot3d(0,(x,0,pi),(y,0,pi))
t = var('t')
my_curve(t)=(sin(t), sin(2*t))
PP=parametric_plot( my_curve, (t, 0, 2*pi), color="purple" )
my_prime=my_curve.diff(t)
L=my_prime(1)*t+my_curve(1) # tangent line at t=1
parametric_plot(L, (t,-2,2))+PP
# Exam
y = var('y')
Plot1=plot_slope_field(2-y,(x,0,3),(y,0,20))
Plot1
y = function('y',x) # declare y to be a function of x
h = desolve(diff(y,x) + y - 2, y, ics=[0,7])
Plot2=plot(h,0,3)
show(expand(h)); show(Plot1+Plot2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment