Skip to content

Instantly share code, notes, and snippets.

@rpietro
Created December 29, 2013 19:00
Show Gist options
  • Save rpietro/8173595 to your computer and use it in GitHub Desktop.
Save rpietro/8173595 to your computer and use it in GitHub Desktop.
algebra and calculus with sage
# script from http://goo.gl/7m0GGp
# Solving Equations Exactly
x = var('x')
solve(x^2 + 3*x + 2, x)
x, b, c = var('x b c')
solve([x^2 + b*x + c == 0],x)
x, y = var('x, y')
solve([x+y==6, x-y==4], x, y)
var('x y p q')
eq1 = p+q==9
eq2 = q*y+p*x==-6
eq3 = q*y^2+p*x^2==24
solve([eq1,eq2,eq3,p==1],p,q,x,y)
solns = solve([eq1,eq2,eq3,p==1],p,q,x,y, solution_dict=True)
[[s[p].n(30), s[q].n(30), s[x].n(30), s[y].n(30)] for s in solns]
# Solving Equations Numerically
theta = var('theta')
solve(cos(theta)==sin(theta), theta)
phi = var('phi')
find_root(cos(phi)==sin(phi),0,pi/2)
# Differentiation, Integration
u = var('u')
diff(sin(u), u)
diff(sin(x^2), x, 4)
x, y = var('x,y')
f = x^2 + 17*y^2
f.diff(x)
f.diff(y)
integral(x*sin(x^2), x)
integral(x/(x^2+1), x, 0, 1)
f = 1/((1+x)*(x-1))
f.partial_fraction(x)
# Differential Equations
t = var('t') # define a variable t
x = function('x',t) # define x to be a function of that variable
DE = diff(x, t) + x - 1
desolve(DE, [x,t])
s = var("s")
t = var("t")
f = t^2*exp(t) - sin(t)
f.laplace(t,s
de1 = maxima("2*diff(x(t),t, 2) + 6*x(t) - 2*y(t)")
lde1 = de1.laplace("t","s"); lde1
de2 = maxima("diff(y(t),t, 2) + 2*y(t) - 2*x(t)")
lde2 = de2.laplace("t","s"); lde2
var('s X Y')
eqns = [(2*s^2+6)*X-2*Y == 6*s, -2*X +(s^2+2)*Y == 3*s]
solve(eqns, X,Y)
var('s t')
inverse_laplace((3*s^3 + 9*s)/(s^4 + 5*s^2 + 4),s,t)
inverse_laplace((3*s^3 + 15*s)/(s^4 + 5*s^2 + 4),s,t)
t = var('t')
P = parametric_plot((cos(2*t) + 2*cos(t), 4*cos(t) - cos(2*t) ),\
show(P)
t = var('t')
p1 = plot(cos(2*t) + 2*cos(t), (t,0, 2*pi), rgbcolor=hue(0.3))
p2 = plot(4*cos(t) - cos(2*t), (t,0, 2*pi), rgbcolor=hue(0.6))
show(p1 + p2
# Euler’s Method
t,x,y = PolynomialRing(RealField(10),3,"txy").gens()
f = y; g = -x - y * t
eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1)
f = lambda z: z[2] # f(t,x,y) = y
g = lambda z: -sin(z[1]) # g(t,x,y) = -sin(x)
P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0)
show(P[0] + P[1])
# Special functions
x = polygen(QQ, 'x')
chebyshev_U(2,x)
bessel_I(1,1).n(250)
bessel_I(1,1).n()
bessel_I(2,1.1).n()
maxima.eval("f:bessel_y(v, w)")
maxima.eval("diff(f,w)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment