Академический Документы
Профессиональный Документы
Культура Документы
1 Imaginary unit
pi = 3.1415927 . . . Pi as an exact value
e e = 2.7182818 . . . Napiers constant e as an exact value
Innity Mathematical Innite
NaN Not a Number
golden_ratio 1.6180 Golden ratio
True true Boolean value
False false Boolean value
sage: True & False
False
sage: True | False
True
2.1.3 Built-In Functions in Sage and operators [1]:
sin(), cos(), tan() Trigonometric functions
asin(), acos(), atan() Arc functions
sinh(), cosh(), tanh() Hyperbolic functions
asinh(), acosh(), atanh() Inverse hyperbolic functions
sqrt(), exp() Square root, e.g. sqrt(2) / exponent
log(), log(a,x) natural logarithm / logarithm of a base x
abs(), sign() Absolute value / sign function
real(z), imag(z) Real & imaginary parts of a complex z
round (x) Rounds to the nearest integer.
ceil (x) Ceiling function
oor (x) Floor function
not not
and and
or or
Compute the following expression by hand and using Sage:
e
ln 7
+ 1
1
/3
+ cos
5
2
10
100
sin
.
The commands used in Sage are the following:
sage: (e^(log(7))+1) ^(1/3) + (cos (5*pi/2) *10^100)*sin(pi/2)
2
which is the same result when compared the answer by hand. Note that log(x) = ln (x) in Sage.
2.1.4 Some Peculiar Functions
factor(x) Returns in vector form, the prime decomposition of x
a % d Calculates a modulus d.
factorial(x) Returns x! if x is a non-negative integer. It also gets calculated if x is any real number.
2.1.5 Complex Arithmetic
Also, complex arithmetic is very simple in Scilab. Compute (3 6i)
2
(3 2i)
3
sage: (3-6*I)^2-(3-2*I)^3
10*I - 18
2
2 INTRODUCTION 2.1 Some Arithmetic Manipulations
2.1.6 Arithmetic on large numbers (integers).
Thanks to the GNU Multiprecision Library (GMP), Sage can handle very large numbers, even numbers with
millions or billions of digits [1].
Lets multiply the following two large numbers:
sage: factorial (250) *3^100
166614144463029630309395806100338934062229552239291090575707188361681753\
550604241739507453792875701142954379356152307754718135315298719620608905\
382458159075203976297501184638579612203851699318192401143156688420363953\
787287168248810746823447954885976994298806653161627146066165572500416684\
007594499976758106055116846729305913456888310043121908808671107133280644\
476544556011460350568290568925821057516798476392218122886770693985789938\
217344616484506910273868061677931208710689914880000000000000000000000000\
0000000000000000000000000000000000000
2.1.7 The N function
The function "N(x)" forces a numerical result if possible (and its not always possible). Heres something
interesting about the function "N(x)":
sage: N(sqrt (17^2+22^2) ,200)
27.802877548915687730654057189532632595638578197646422961214
The second argument to "N(x)" species the number of binary bits in the result. This means function "N(x)"
is actually dened as "N(x,b)" but the "b" is optional. Heres another "N(x,b)" example:
N(pi,digits=100)
3.1415926535897932384626433832795028841971693993751058209749445923078164\
06286208998628034825342117068
2.1.8 Exercises
** Compute the following arithmetic expressions:
34/17 + (15 13 12 + 47)
2
sin(cos(e
ln
2
)) + 98(55/7 1000 tan(
4
))
** Simplify the following expression rst by hand and then using Sage:
ln (3 + 2) + ln (3 2)
ln (3 + 2) ln (3 2)
.
** Obtain a text le displaying the value of 123
13
5
and calculate its number of digits (theres an fast way to
do this).
** Obtain a text le containing the rst 100,000 digits of pi using the N function.
** Compute the following expression in Sage
(+ 3) 2 3 ln (1/) .
** Using Sage, determine if 49256033 is prime.
** In the sequence of numbers 12, 121, 1211, 12111, 121111, ... nd the rst one to be a prime. [mathoverow]
3
2 INTRODUCTION 2.2 Some Algebra
2.2 Some Algebra
2.2.1 Polynomial manipulation
sage: p=var('p')
sage: (((p-1) ^2+1) ^2*(p-2) ^2*(p+3)^2).expand ()
p^8 - 2*p^7 - 11*p^6 + 40*p^5 - 16*p^4 - 144*p^3 + 340*p^2 - 336*p + 144
2.2.2 Computing a Taylor Series
Example. Obtain the Taylor series of the function f(x) = log (1 + x) about x
0
= 1.
sage: taylor(ln(x), x, 1, 8)
-1/8*(x - 1)^8 + 1/7*(x - 1)^7 - 1/6*(x - 1)^6 + 1/5*(x - 1)^5 - 1/4*(x
- 1)^4 + 1/3*(x - 1)^3 - 1/2*(x - 1)^2 + x - 1
Besides that we can obtain an expression for the Taylor polynomials in 2 dimensions, the next example comes
from the book of Burden:
sage: t,y=var('t,y')
sage: taylor(exp ( -1/4*(t-2) ^2 -1/4*(y-3) ^2)*cos (2*t+y-7) ,(t,2) ,(y,3) ,2)
-3/4*(y - 3)^2 - 2*(y - 3)*(t - 2) - 9/4*(t - 2)^2 + 1
2.2.3 Solve command
Solve equations exactly.
sage: x=var('x')
sage: solve(x^2 + 3*x + 2, x)
[x == -2, x == -1]
sage: a,b,c,d,x=var('a,b,c,d,x')
sage: solve([a*x^3 + b*x^2 + c*x + d == 0],x)
[x == -1/2*(I*sqrt (3) + 1) *(1/18* sqrt (27*a^2*d^2 + 4*a*c^3 - b^2*c^2 -
2*(9*a*b*c - 2*b^3)*d)*sqrt (3)/a^2 - 1/54*(27*a^2*d - 9*a*b*c + 2*b^3)/
a^3) ^(1/3) - 1/3*b/a + 1/18*( -I*sqrt (3) + 1)*(3*a*c - b^2) /((1/18* sqrt
(27*a^2*d^2 + 4*a*c^3 - b^2*c^2 - 2*(9*a*b*c - 2*b^3)*d)*sqrt (3)/a^2 -
1/54*(27*a^2*d - 9*a*b*c + 2*b^3)/a^3) ^(1/3)*a^2), x == -1/2*(-I*sqrt
(3) + 1) *(1/18* sqrt (27*a^2*d^2 + 4*a*c^3 - b^2*c^2 - 2*(9*a*b*c - 2*b
^3)*d)*sqrt (3)/a^2 - 1/54*(27*a^2*d - 9*a*b*c + 2*b^3)/a^3) ^(1/3) -
1/3*b/a + 1/18*(I*sqrt (3) + 1)*(3*a*c - b^2) /((1/18* sqrt (27*a^2*d^2 +
4*a*c^3 - b^2*c^2 - 2*(9*a*b*c - 2*b^3)*d)*sqrt (3)/a^2 - 1/54*(27*a^2*d
- 9*a*b*c + 2*b^3)/a^3) ^(1/3)*a^2), x == (1/18* sqrt (27*a^2*d^2 + 4*a*c
^3 - b^2*c^2 - 2*(9*a*b*c - 2*b^3)*d)*sqrt (3)/a^2 - 1/54*(27*a^2*d - 9*
a*b*c + 2*b^3)/a^3) ^(1/3) - 1/3*b/a - 1/9*(3*a*c - b^2) /((1/18* sqrt (27*
a^2*d^2 + 4*a*c^3 - b^2*c^2 -2*(9*a*b*c - 2*b^3)*d)*sqrt (3)/a^2 -
1/54*(27*a^2*d - 9*a*b*c + 2*b^3)/a^3) ^(1/3)*a^2)]
Solve systems of Equations:
sage: x1,x2 ,x3 ,a,b,c = var('x1 ,x2 ,x3 ,a,b,c')
sage: eq1 = 2*x1 -x2 + x3 == a
sage: eq2 = -3*x1 +x2 - 1*x3 == b
sage: eq3 = 15*x1 - 2*x2 ==c
sage: solve([eq1 ,eq2 ,eq3],x1,x2,x3)
4
2 INTRODUCTION 2.2 Some Algebra
yield the solutions:
x
1
= a b, x
2
=
15
2
a
15
2
b
1
2
c and x
3
=
9
2
a
11
2
b
1
2
c.
2.2.4 Partial Fractions
v=var('v')
f=(v+1)/(v^2+4*v)
f.partial_fraction(v)
3/4/(v + 4) + 1/4/v
2.2.5 Function denition
sage: x=var('x')
sage: def f1(x): return 2*cos(x)+3* sin(x)
sage: def f2(x): return 3*cos(x) -2*sin(x)
sage: f1(3*pi)
-2
sage: (f1(x)*diff(f2(x),x)-f2(x)*diff(f1(x),x)).trig_simplify ()
-13
2.2.6 Innite sums
p=var('p')
assume(p,'integer ')
assume(p>0)
sum((x)**( -8), x, 1, Infinity)
1/9450* pi^8
2.2.7 Integration and dierentiation
Dierentiation.
sage: diff(tan(x),x)
tan(x)^2 + 1
sage: diff(tan(x),x,x,x)
4*( tan(x)^2 + 1)*tan(x)^2 + 2*(tan(x)^2 + 1)^2
sage: diff(exp(x)*sin(x) ,101)
-1125899906842624*e^x*sin(x) - 1125899906842624*e^x*cos(x)
Integration.
sage: var('x')
sage: integral( (sqrt(x^2+1)-sqrt(x^2-1)) / (sqrt(x^4-1)) , x )
log (2*x + 2*sqrt(x^2 - 1)) - arcsinh(x)
2.2.8 Laplace transforms
Laplace transform
sage: var('s,t')
sage: f = 2*t^2* exp(t) - t*sin(t)
sage: f.laplace(t,s)
-2*s/(s^2 + 1)^2 + 4/(s - 1)^3
5
2 INTRODUCTION 2.3 List of variables
Inverse Laplace transforms
s,t = var('s,t')
inverse_laplace (1/(s^2+1)^2, s, t)
-1/2*t*cos(t) + 1/2* sin(t)
2.3 List of variables
sage: # first make a list of the variables
sage: n = 3
sage: s = list(var('s_%d' % i) for i in range (2*n))
sage: w = list(var('w_%d' % i) for i in range (2*n))
sage: s
[s_0 , s_1 , s_2 , s_3 , s_4 , s_5]
sage: w
[w_0 , w_1 , w_2 , w_3 , w_4 , w_5]
sage:
sage: # then make a list of equations
sage: eqs = list(w[k] == s[2*n-k-1] for k in range (2*n))
sage: eqs
[w_0 == s_5 , w_1 == s_4 , w_2 == s_3 , w_3 == s_2 , w_4 == s_1 , w_5 == s_0]
2.4 Exercises.
1. Mllers method consist of nding a fourth iterate by obtaining the intersection of the x-axis and the
quadratic interpolating polynomial of the former three. To do this, on the polynomial
P(x) = a (x p
k+2
)
2
+ b (x p
k+2
) + c,
the conditions P(p
i
) = f(p
i
) for i = k, k + 1, k + 2 are set. Using Sage, nd the coecients a, b and c
that satisfy this conditions.
2.5 Exercises
1. Consider the following three methods for approximating the solution of initial value problem:
Midpoint Method:
w
0
= ; w
i+1
= w
i
+ hf
t
i
+
h
2
, w
i
+
h
2
f (t
i
, w
i
)
, for each i = 0, 1, . . . , N 1.
Modied Euler Method:
w
0
= ; w
i+1
= w
i
+
h
2
[f (t
i
, w
i
) + f (t
i+1
, w
i
+ hf (t
i
, w
i
))] , for each i = 0, 1, . . . , N 1.
Heuns Method:
w
0
= ; w
i+1
= w
i
+
h
4
f (t
i
, w
i
) + 3f
t
i
+
2
3
h, w
i
+
2
3
hf (t
i
, w
i
)
, for each i = 0, 1, . . . , N 1.
Using Sage, show that the three methods are identical for y
1
(t) = u
2
(t)
u
2
(t) = e
2t
sin t 2u
1
(t) + 2u
2
(t)
subject to the initial conditions: u
1
(0) = 0.4, u
2
(0) = 0.6.
If we were to use the standard procedure we will need to do the following
t=var('t')
u1 = function ('u1 ',t)
u2 = function ('u2 ',t)
de1 = diff(u1,t) == u2
de2 = diff(u2,t) == -2*u1 +2*u2 + exp (2* t)*sin(t)
desolve_system ([de1 , de2], [u1,u2],ics =[0 ,-0.4 ,-0.6])
However, the method used to solve these kind of dierential equations is the Laplace transforms method,
and Sage has not been completed to handle cases where the transformed variable s need to take on several
ranges. We obtain the following error message:
Traceback (click to the left of this block for traceback)
...
TypeError: ECL says: Maxima asks: Is ?g4442-2 positive, negative, or zero?
Notice that the error is centered around the inability of the software to be able to determine the sign of
?g4442-2. In order to x this problem we made a change of variables, changing t t we generate a new
system, here we need to solve:
t=var('t')
u1 = function ('u1 ',t)
u2 = function ('u2 ',t)
de1 = diff(u1,t) == -u2
de2 = diff(u2,t) == 2*u1 -2*u2 + exp(-2* t)*sin(t)
desolve_system ([de1 , de2], [u1,u2],ics =[0 ,-0.4 ,-0.6])
and we obtain as solutions:
[u1(t) == -1/5*(sin(t) + 2*cos(t))*e^(-2*t), u2(t) == -1/5*(4* sin(t) + 3*
cos(t))*e^(-2*t)]
now, reverting the use of the change of variables by applying again t t we obtain that the sol. of the
PVI: is
u
1
(t) =
1
5
(sin t 2 cos t) e
2t
u
2
(t) =
1
5
(4 sin t 3 cos t) e
2t
4.4 Slope Fields
Exercise: Write the slope eld of the dierential equation
dy
dx
= xsin x y (1)
for x [3, 3] and y [3, 3].
The following sage commands initiate the variables and execute the plot_slope_eld to generate the desired
slope eld.
11
4 DIFFERENTIAL EQUATIONS 4.5 Solution Curves
sage: x,y = var('x y')
sage: plot_slope_field(x*sin(x)-y, (x,-3,3), (y,-3,3),color='blue ')
Here is the output:
Figure 1: Slope eld for the ODE in (1)
4.5 Solution Curves
Exercise. Plot the slope eld for the following rst order dierential equation:
dy
dx
= xy on [1, 1] [1, 1]
and plot the solution curve that passes through (0, 0.5).
sage: #create and save image of slope field
sage: u,v=var('u,v')
sage: SlopeField=plot_slope_field(u*v,(u,-1,1) ,(v,-1,1))
sage: #generate ans save image of solution curve using 'desolve '
sage: x=var('x')
sage: y=function('y',x)
sage: f=desolve(diff(y,x)==x*y,y,[0 ,0.8])
sage: SolnPlot=plot(f,(x,-1,1),ymax =1)
sage: (SlopeField+SolnPlot).show()
4.6 Exact Solutions
x = var ('x')
y = function ('y',x)
DE = diff (y,x) -x + y == 0
sol =[]; i=0; a=0; b=0;
pts=points ([],size=20, color='red ')
12
4 DIFFERENTIAL EQUATIONS 4.7 Numerical solution curves
#loop over to obtain the sequence of plots
while i < 30:
#randomly choose points in the [ -10 ,10]^2 space
a=20* random () -10
b=20* random () -10
#append the solutions whose initial condition was chosen randomly
sol.append (desolve (DE , [y, x], ics =[ a, b]))
#graph the initial condition
pts=pts+points ([a,b],size=20,color='red ')
i=i+1
g= plot (sol , x, -10, 10)
(g+pts).show(ymin = -10, ymax =10)
4.7 Numerical solution curves
4.7.1 A quick example.
from sage.calculus.desolvers import desolve_rk4
x,y=var('x,y')
slopefield=plot_slope_field(-x^2+ sin(y) ,(x,-3,3) ,(y,-3,3))
f=line(desolve_rk4(-x^2+sin(y),y,ics=[1,-3], end_points =[-2.5,3], step =0.05)
)
(slopefield+f).show(xmin=-3,xmax=3,ymin=-3,ymax =3)
13
4 DIFFERENTIAL EQUATIONS 4.8 Direction Field and Solutions
4.8 Direction Field and Solutions
Exercise. Write the Van der Pol equation as a system of dierential equations of order 1, plots its direction
eld on [2, 2] [2, 2] and solution curves that passes through the points (0.5, 0.5), (0.75, 0.75), (1.0, 1.0)
and (2.0, 2.0).
Solution.
The van der Pol equation, x
1 x
2
x
1
= x
2
x
2
=
1 x
2
1
x
2
x
1
For = 1. The following yields the direction eld and sample solutions:
sage: from sage.calculus.desolvers import desolve_odeint
sage: x1,x2 ,epsilon=var('x1 ,x2 ,epsilon ')
sage: epsilon =1 #epsilon =1 has been chosen
sage: f=[x2 ,epsilon *(1-x1^2)*x2-x1] #function defining the system
sage: #obtaining the direction field
sage: field1=plot_vector_field(f, (x1 ,-3,3), (x2 ,-3,3))
sahe: #obtaining a delimited solution
sage: sol1=desolve_odeint(f,[0.5 ,2] , srange (0 ,10 ,0.05) ,[x1 ,x2])
sage: p1=line(zip(sol1[:,0],sol1 [:,1]),xmin=-3,ymin=-3,xmax=3,ymax =3)
sage: #Using zip to intertwine the component rows and line function to
thefine the line
sage: (p1+field1).show()
14
4 DIFFERENTIAL EQUATIONS 4.9 Chaos
4.9 Chaos
sage: #Lorenz attractor with sigma=10, r=25 and b=-1/3
sage: from sage.calculus.desolvers import desolve_odeint
sage: x,y,z=var('x,y,z')
sage: f=[-10*x+10*y,25*x-y-x*z,-8*z/3+x*y]
sage: sol=desolve_odeint(f,[-1,-1,1], srange (0 ,100 ,0.05) ,[x,y,z])
sage: p=line(zip(sol[:,0],sol[:,1],sol [:,2]),thickness=3,rgbcolor
=(1/4 ,1/8 ,3/4))
sage: p.show()
15
6 PROGRAMMING IN SAGE
5 Numerical Routines of a function
5.1 Finding the maximum of a function
sage: x=var('x')
sage: g=abs(2*x*cos (2*x) -(x-2)^2)
sage: g.find_maximum_on_interval (2,4)
(4.9814339575530084 , 3.1311062764376052)
5.2 Finding roots numerically on a polynomial
sage: import numpy
sage: f = numpy.array ([1,-2,-11,40,-16,-144,340,-336,144])
sage: numpy.roots(f)
array ([ -3.00000005 +0.00000000e+00j, -2.99999995 +0.00000000e+00j,
2.00000000 +6.44817148e-08j, 2.00000000 -6.44817148e-08j,
1.00000001 +1.00000004e+00j, 1.00000001 -1.00000004e+00j,
0.99999999 +9.99999955e-01j, 0.99999999 -9.99999955e-01j])
5.3 Finding roots numerically
sage: x=var('x')
sage: find_root(sqrt(x)-sin(x)==2,4,10)
8.3341883677787916
6 Programming in Sage
6.1 Introduction
6.1.1 Loading scritpts
Sage scripts can be save under the sage extension as in example.sage which can then be uploaded on the
Data menu selecting Upload or create le...
The le contain the following commands:
print N(pi, digits =10)
print sqrt (1)+sqrt (2)+sqrt (3)
16
6 PROGRAMMING IN SAGE 6.2 Write to an external le
The le can now be executed.
sage: load DATA+'example.sage '
3.141592654
sqrt (2) + sqrt (3) + 1
6.1.2 Creating simple functions
The following converts from degrees to radians
sage: toRadians(theta)=theta*pi/180
sage: toRadians (180)
pi
6.1.3 if - elif - else
def passMATH(x): #callable function pass(x)
if x>=70:
return 'passed '
elif x>=60 and x<70:
return 'low pass '
else:
return 'failed '
6.2 Write to an external le
f = file('multiplication_table.txt ','w')
for i in range (11):
for k in range (1,10):
f.write(str(k)+'x'+str(i)+'='+str(k*i)+'\t')
f.write('\n')
f.close()
The generated le multiplication_table.txt has the following content:
1x0=0 2x0=0 3x0=0 4x0=0 5x0=0 6x0=0 7x0=0 8x0=0 9x0=0
1x1=1 2x1=2 3x1=3 4x1=4 5x1=5 6x1=6 7x1=7 8x1=8 9x1=9
1x2=2 2x2=4 3x2=6 4x2=8 5x2=10 6x2=12 7x2=14 8x2=16 9x2=18
17
REFERENCES
1x3=3 2x3=6 3x3=9 4x3=12 5x3=15 6x3=18 7x3=21 8x3=24 9x3=27
1x4=4 2x4=8 3x4=12 4x4=16 5x4=20 6x4=24 7x4=28 8x4=32 9x4=36
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25 6x5=30 7x5=35 8x5=40 9x5=45
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36 7x6=42 8x6=48 9x6=54
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49 8x7=56 9x7=63
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64 9x8=72
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
1x10=10 2x10 =20 3x10=30 4x10 =40 5x10=50 6x10 =60 7x10=70 8x10 =80 9x10=90
7 Others
7.1 Subsection
7.1.1 Other bases, why is not OK to put zeroes to the left of integers
http://nb.hssagemath.org/home/pub/101/
References
[1] A Tour of Sage. Sage Tour v5.6. http://www.sagemath.org/doc/a_tour_of_sage/. Accessed
on January 27, 2013.
[JK] http://www.sagemath.org/doc/reference/sage/symbolic/constants.html
[3] http://ask.sagemath.org/question/363/a-list-of-symbolic-variables
[mathoverow] http://mathoverow.net/questions/15444/
18