Professional Documents
Culture Documents
MScPythonPracts 231020 223819
MScPythonPracts 231020 223819
V.N.Purushothaman
Department of Physi s
November 3, 2011
Contents
1 Numeri al Methods in PYTHON 1
1.1 Lagrange's Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Polynomial Evaluation: Bessel's Fun tion . . . . . . . . . . . . . . . . 3
1.3 Polynomial Evaluation: Legendre Fun tion . . . . . . . . . . . . . . . 4
1.4 Least Square Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Monte Carlo Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Newton-Raphson Iterative Method . . . . . . . . . . . . . . . . . . . 9
1.7 Runge-Kutta Method . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.8 Numeri al Integration . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2 Simulation of Physi al Phenomena 15
2.1 Lennard-Jones potential . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Two-slit photon interferen e . . . . . . . . . . . . . . . . . . . . . . . 16
2.3 Random Walk in One-Dimension . . . . . . . . . . . . . . . . . . . . 18
2.4 Random Walk in Two-Dimensions . . . . . . . . . . . . . . . . . . . . 20
2.5 Motion in a Central For e Field:- Rutherford S attering . . . . . . . . 23
2.6 Logisti equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.7 Simulation of Kepler's First and se ond Laws . . . . . . . . . . . . . 27
2.8 Simulation of Kepler's Third Law . . . . . . . . . . . . . . . . . . . . 30
Prefa e
This book originated from my experien e as an instru tor and examiner of Final M.S
Physi s students for the past few years. The subje t matter is arranged in the order
of in reasing algorithmi omplexity rather than the depth of prin iples involved.
Most of the variables are given the same name in program and algorithm to fa ilitate
readability. The names are also similar to those in onventional physi s textbooks.
I
1
Aim
To interpolate the value of a fun tion using Lagrange interpolating polynomial.
Prin iple
The te hnique for interpolating y = y(x) is to t an approximate polynomial y ≅ f (x)
through the points (xi , yi ) in the neighborhood of the point x where the value of y
is required. Let there be n points xi where the values yi are given. A polynomial of
degree n − 1 ould be used for interpolating. In indLagrange method the polynomial
is hosen in the following form
n n
(x − xj )
(1)
X Y
y ≅ f (x) = yi
i=1 j=1,j6=i
(xi − xj )
Algorithm
1: Read x, n
2: for i = 1 to n step 1 do
3: Read (xi , yi )
4: end for
5: sum ← 0
6: for i = 1 to n step 1 do
7: product ← 1
8: for j = 1 to n step 1 do
9: if i 6= j then
2 1 NUMERICAL METHODS IN PYTHON
(x − xj )
10: product ← product ×
(xi − xj )
11: end if
12: end for
13: sum ← sum + yi × product
14: end for
15: print sum
16: End
Program
x,y,produ t=[℄,[℄,[℄
n=input('How Many Data points n? ')
for i in range(n):
x.append(input('value of x'))
y.append(input(' orresponding value of y'))
ux=input('What is the value of x at whi h y is required?')
for i in range(n):
p=1
for j in range(n):
if i!=j: p*=(ux-x[j℄)/(x[i℄-x[j℄)
produ t.append(p*y[i℄)
print 'The value of y at given x is', sum(produ t)
Result
Values of y for dierent x is al ulated using dierent sets of [xi , yi]
Observations
Label Data (xi , yi )n UX y
x
y
x
y
x
y
Aim
To evaluate the Bessel Fun tion of any order n for any value of x.
1.2 Polynomial Evaluation: Bessel's Fun tion 3
Prin iple
The Bessel fun tion of order n for a variable x is given by the series
∞
(−1)s x 2s+n
(2)
X
Jn (x) =
s=0
s!(n + s)! 2
1 x n
The zeroth term (s = 0) of the expansion is . The ratio of the pth and
n! 2
−1 x 2
(p − 1)th term of the expansion is . using these results Bessel fun tion
p(n + p) 2
of any order an be al ulated for any desired a ura y.
Algorithm
1: Read order n, variable x and desired a ura y e
2: f act ← 1 ⊲ f act represents n!
3: for i=2 to n step 1 do
4: f act = f act.i
5: end for
1 x n
6: term ←
f act 2
7: sum ← term
8: p ← 1
9: while |term| > e do
−1 x 2
10: term ← term.
p(n + p) 2
11: sum ← sum + term
12: p←p+1
13: end while
14: Print sum ⊲ sum gives Jn (x)
Program
term=[℄
n,x,e=input('Give Order n, value x and required a ura y e of Bessel fun tion')
x/=2.0
fa torial=1
for i in range(1,n+1):fa torial*=i
term.append(x**n/fa torial)
for i in range(1,1000):
term.append(-term[i-1℄*x*x/(i*(i+n)))
if abs(term[i℄)< e:break
print 'J%d(%f)=%f'%(n,x,sum(term))
4 1 NUMERICAL METHODS IN PYTHON
Result
The value of Bessel fun tion for dierent orders and dierent values of variable are
found and tabulated.
Observations
Order n Value of x Value of Bessel fun tion
Aim
To evaluate the Legendre Fun tion of any order n for any value of x.
Prin iple
Legendre fun tion Pn (x) are dened through a generating fun tion as
∞
1
(3)
X
√ = Pn (x)tn
1 − 2xt + t2 n=0
where |t| ≤ 1 The zeroth term (n = 0) of the expansion is 1 = P0 (x)t0 Hen e P0 (x) = 1
for all x. Expanding left side as a binomial series and equating oe ient of t on both
sides, xt = P1 (x)t or P1 (x) = x for all x. Dierentiating and equating oe ients of
tn on both sides one gets
(2n + 1)xPn (x) − nPn−1 (x)
Pn+1 (x) = (4)
n+1
This is a re urren e relation whi h may be used for al ulating Legendre polynomials
of any order.
Algorithm
1: Read n, x
2: P0 (x) ← 1
3: P1 (x) ← x
4: if n=0 then
5: Print P0 (X) = 1
6: end if
7: if n=1 then
8: Print P1 (X) = x
9: end if
10: if n > 1 then
1.4 Least Square Fitting 5
11: for i = 1 to n − 1 do
(2i + 1)xPi (x) − iPi−1 (x)
12: Pi+1 (x) ←
i+1
13: pi−1 (x) ← pi (x)
14: pi (x) ← pi+1 (x)
15: end for
16: end if
17: Print Pn (x)
18: End
Program
n,x,e=input('Give Order n, value x and error e of Legendre fun tion')
p0,p1=1,x
if n==0:print 'p0(x)=1.0'
if n==1:print 'p1(%0.5f)=%0.5f'%(x,x)
if n>1:
for i in range(1,n):
p=((2*i+1)*x*p1-i*p0)/(i+1)
p0,p1=p1,p
print 'p%d(%0.5f)=%0.5f'%(n,x,p)
Result
Observations
Order n Value of x Value of Legendre fun tion
Aim
To nd the slope and inter ept of the linear least square t of the given data. Also
to al ulate the most probable value of y for given x
Prin iple
When the data obtained is a urate, Interpolation by polynomial tting gives good
results. If data has errors, as in the ase of experimentally generated data, a urve an
be tted only approximately. This must be statisti ally a best t. It an be shown
that the best t is obtained if the sum of squares of deviations from the approximate
urve is minimum. This is alled least squares approximation. If the urve tted is a
straight line, it is alled linear least squares approximation.
6 1 NUMERICAL METHODS IN PYTHON
Let ȳi = mxi + c be the a tual straight line to be tted. Let (xi , yi )n be the n data
points to be tted. Then deviation Di = yP i −y ¯i . ForPbest t it an be shown that
∂ Di2 ∂ Di2
2
must be a minimum. As 2
, = 0 is the ondition for
P
i D i D i ≥ 0 =
∂m ∂c
minimum. Substituting Di = yi − mxi − c and simplifying one gets
(5)
X X X
m x2i + c xi = xi yi
(6)
X X
m xi + nc = yi
mr + cp = s and mp + nc = q (7)
Solving
pq − ns
m= (8)
p2 − nr
ps − qr
c= 2 (9)
p − nr
Algorithm
1: Read number of data points n
2: Sum of x−values p ← 0
3: Sum of y−values q ← 0
4: Sum of x2 −values r ← 0
5: Sum of xy−values s ← 0
6: for i=1 to n do
7: Read pair (xi , yi )
8: p ← p + xi
9: q ← q + yi
10: r ← r + x2i
11: s ← s + xi yi
12: end for
pq − ns
13: m ← 2
p − nr
ps − qr
14: c ← 2
p − nr
15: Print m and c
16:
17: Read ux where y is required
18: uy ← mx + c
19: print uy
20: End
1.5 Monte Carlo Method 7
Program
from numpy import*
n=input('Number of data points n')
x=array([input('X-values for fitting') for i in range(n)℄)
y=array([input('Corresponding Y-values') for i in range(n)℄)
p,q,r,s=sum(x),sum(y),sum(x*x),sum(x*y)
m=(n*s-p*q)/(n*r-p**2)
=(q*r-p*s)/(n*r-p**2)
print 'y=%0.6f x+%0.6f'%(m, )
ux=input('x-value for whi h y is required')
print 'y(%0.5f)=%0.5f'%(ux,m*ux+ )
Result
The slope and inter ept for dierent sets of data are found. Using this slope and
inter ept values of y orresponding to dierent values x are al ulated
Observations
var. data (Xi , Yi ) M C UX UY
xi
yi
xi
yi
xi
yi
Aim
To nd the value of π using random numbers.
Prin iple
(0,1)
...................... (1,1)
.................
............
...........
..........
........
........
.......
.......
......
......
......
.....
.....
.....
....
....
....
....
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
(1,0)
...
...
...
.
(0,0)
8 1 NUMERICAL METHODS IN PYTHON
Points in the rst quadrant of a unit ir le entered at origin satises the following
inequalities.
1. 0 ≤ x ≤ +1
2. 0 ≤ y ≤ +1
3. x2 + y 2 ≤ 1 .
.The rst two onditions are satised by all points in a unit square in the rst quadrant
as shown in gure. The ratio of area of the se tor(= π/4) to the area of the square(=
12 ) is π/4. Four times this ratio gives the value of π .
To determine this ratio in Monte Carlo Method, pairs of pseudo-random numbers
in the range (0, 1) are generated for oordinates (x, y). All these p pairs fall within
the square, but only those points belong to the ir le for whi h x2 + y 2 ≤ 1. The
number of su h points N are ounted. The ratio of number N to the total number of
points gives the ratio of their areas.
In PYTHON there is one in-built random number generator using the multipli a-
tive ongruential re ursive method developed by D.Lehmer. The ith and (i + 1)th
random numbers are related as
xi+1 = (axi + c)mod m (10)
where the multiplier a = 75 − 1 = 16, 806, the in rement c = 0 and the modulus
m = 231 − 1 = 2, 14, 74, 83, 647 are alled magi numbers. The re urren e relation
suggests that the random numbers will repeat with a period less than m. The magi
numbers for the set (a, m, c) are hosen so that period is ≅ m and every number
between 0 and m − 1 o ur at some point. The role of initial seed x0 has only little
ee t.
Algorithm
To generate random numbers
fun tion rand()
1: if xi = 0 then
2: xi ← 1
3: end if
4: a ← 16806
5: c←0
6: m ← 2147483647
7: xi+1 ← (axi + c)mod m
8: Return xi+1 /m
9: xi ← xi+1
10: End
To al ulate value of π
1: Read N ,the ount of random numbers to be generated
1.6 Newton-Raphson Iterative Method 9
2: j ← 0
3: for i = 1 to N do
4: x ← rand()
5: y ← rand()
6: if (x2 + y 2 ) ≤ 1 then
7: j ←j+1
8: end if
9: end for
10: π ← 4.j/i
11: Print π
12: End
Program
from random import random
j=0
for i in range(1000000):
if (random()**2+random()**2)<=1:j+=1
print "Value of pi = ",4.0*j/i
Result
The value of π is al ulated using various large sets of random numbers and tabulated.
Aim
To nd the roots of polynomial and trans endental equations.
Prin iple
The Taylor series expansion of a fun tion f (x) is given by
∞
(x − x0 )n f (n) (x0 )
(11)
X
f (x) =
n=0
n!
where f (n) (x0 ) is the nth − derivative of f (x) at x = x0 . Hen e the value of f (x) at
x = xi+1 about x = xi is given by
∞
(xi+1 − xi )n f (n) (xi )
(12)
X
f (xi+1 =
n=0
n!
If xi+1 is a root of f (x) in this approximate form, then f (xi+1 ) = 0. Substituting and
rearranging
f (xi )
xi+1 = xi − (14)
f (1) (xi )
To get the a tual root within a pres ribed error limit, this expression may be iterated
with the urrent xi+1 as the new xi . If xi happens to be near the a tual root, a small
number of iterations will give the a tual root. Hen e the initial guess of the root is
important.
Algorithm
1: Read initial guess x0 , error e,number of iterations n, and minimum slope s
2: for i = 1 to n do
3: f ← f (x0 )
4: g ← f (1) (x0 )
5: if g < s then
6: 'Slope too small to onverge to a root'
7: Goto line:16
8: end if
9: x ← x0 − (f /g)
10: if |(x − x0 )/x| < e then
11: Print x
12: Goto line:16
13: end if
14: end for
15: Print 'Do not onverge to a root within n-iterations.
16: End
Program
from math import *
def f(x):return x**3-3.0*x-5.0
def g(x):return 3.0*x**2-3.0
i,x1=0,0.0
x=input('Initial guess of the root')
while abs(g(x))>0.001 and abs(f(x))>1.0e-6:
x1=x-f(x)/g(x)
x=x1
i+=1
print "Iterations= %d \t,x1= %5.3f,\t f(x1)= %10.3e"%(i,x1,f(x1))
Result
THE ZEROS OF A FEW FUNCTIONS ARE FOUND AND ARE TABULATED
1.7 Runge-Kutta Method 11
Observations
F (X) X0 N E S Root F(ROOT)
X 2 + 5X + 6 -5 5 0.001 0.0001 -3.00000 0
X 2 + 5X + 6 2 2 0.0001 0.0001 -2.00000 0
5X 5 − 2 cos X 0.1 16 .0001 0.0001 0.7779492 7 × 10−7
10e−X + 16 sin2 (X) 10 6 0.001 0.001 9.430085 1.2 × 10−3
10e−X + 16 sin2 (X) 15 6 0.001 0.001 15.69952 1.14 × 10−3
Aim
To solve a rst order dierential equation by Runge-Kutta fourth order method.
Prin iple
dy
Consider a dierential equation = f (x, y) with the initial ondition y(x0 ) = y0 .
dx
dy
If s = is the average slope of the fun tion between x0 and x0 + δx, then
dx mean
y(x0 + δx) = y(x0 ) + s.δx In Runge-Kutta fourth order method, s is found as the
weighted average of slopes at dierent points between x0 and x0 + δx as follows.
dy
• Cal ulate slope s1 at x0 ; s1 = = f (x0 , y0).
dx
• Cal ulate y at (x0 + δx/2) using s1 ; y1 = y(x0 + δx/2) = y0 + s1 .δx/2
• Cal ulate on e again the slope s3 at (x0 + δx/2) using y2 ; s3 = f (x0 + δx/2, y2).
Algorithm
1: Read x0 , y0 , n, x1
2: δx ← (x1 − x0 )/n
3: for i = 1 to n step 1 do
4: s1 ← f (x0 , y0 )
5: s2 ← f (x0 + δx/2, y0 + s1 δx/2)
6: s3 ← f (x0 + δx/2, y0 + s2 δx/2)
12 1 NUMERICAL METHODS IN PYTHON
Program
Finds y(ux) using (x0 , y0 ) and the equation dy/dx = (y − x)/(y + x)
def f(x,y): return (y-x)/(y+x)
def rk4(x, y, fxy, h,n):
for i in range(1,n+1):
k1 = h * fxy(x, y)
k2 = h * fxy(x + h/2.0, y+k1/2.0)
k3 = h * fxy(x + h/2.0, y+k2/2.0)
k4 = h * fxy(x + h, y+k3)
y += ( k1 + 2*k2 + 2*k3 + k4 )/6.0
x+=h
return y
Result
Observations
dy/dx = x0 y0 x1 n y(x1 )
2x2 0 1 2 10 6.3333
x+y 1 1 3 15 18.1670700
xy 1 1 4 20 1804.628000
ye−x 2 1 3 40 1.089314
Aim
To evaluate denite integrals of tabulated fun tions using Newton-Cotes Integration
formulae.
Prin iple
The basi strategy is to repla e a ompli ated fun tion f (x) or tabulated data by
a ollo ation polynomial p(x) so that integration be omes easy. Trapezoidal rule
1.8 Numeri al Integration 13
for integration uses straight lines (rst order polynomial) to onne t data points
equispa ed in x. If f (x1 ) and f (x2 ) are given, then a line from (x1 , f (x1 )) to (x2 , f (x2 ))
is given by
f (x2 ) − f (x1 )
f (x) = f (x1 ) + (x − x1 ) (15)
x2 − x1
Z x2 Z x2
f (x2 ) − f (x1 )
I = f (x)dx ≅ f (x1 ) + (x − x1 ) dx (16)
x1 x1 x2 − x1
f (x2 ) + f (x1 )
= (x2 − x1 ) (17)
2
The integration is thus repla ed by summation. This is alled Trapezoidal rule as
eq.17 represents area of a Trapezoid bounded by parallel sides f (x1 ), f (x2 ), the
straight line (x1 , f (x1 )) to (x2 , f (x2 )) and the x-axis. If data is available for n + 1
equispa ed points (xi ) between x1 and xn+1 ,
n
f (x1 ) + f (xn+1 )
(18)
X
I = h +h f (xj )
2 j=2
where h = xj − xj−1 .
In Simpson's method, higher order ollo ation polynomials are employed. If a
quadrati fun tion is tted to represent a set of three data points (x1 , y1), (x2 , y2) and
(x3 , y3 ), the integral may be approximated by Legrange polynomial to get
Z x3
I = f (x)dx (19)
x
Z 1x3
(x − x2 )(x − x3 ) (x − x1 )(x − x3 ) (x − x1 )(x − x2 )
≅ f (x1 ) + f (x2 ) + f (x3 ) dx
x1 (x1 − x2 )(x1 − x3 ) (x2 − x1 )(x2 − x3 ) (x3 − x1 )(x3 − x2 )
Algorithm
To ompute the denite integral of a tabulated fun tion
1: Read number n of data points (xi , yi ) for tabulated fun tion or the limits of
integration if fun tional form is given.
2: Find or assign a value for interval h
3: sum ← 0
14 1 NUMERICAL METHODS IN PYTHON
Program
To nd (1 + x)−1 dx using Trapezoidal rule and Simpson's 1/3 rule
Rb
a
Result
A few fun tions and a few tabulated values were substituted and the integrals were
found to be nearly a urate.
15
Observations
Integral data points Trapezoidal Simpson's Analyti al
9999 197.939 197.939 198.02
R 3 2x
e dx
R14 2
R24
3x dx 9999 55.99 55.99 56.00
R22π
x sin(x/2)dx 9999 0.162489 0.162489
0
dx/(2 + cos x 9999 3.6274 3.62734 3.6275987
Aim
To plot the attra tive and repulsive parts of the Lennard-Jone's potential for various
values of parameters.
Prin iple
Two distin t for es a t on neutral atoms and mole ules. An attra tive van der Waal's
for e at a large distan e and a for e of repulsion at a short distan e whi h is a
onsequen e of the overlapping ele tron orbitals (Pauli repulsion). The Lennard-
Jone's potential is a simple mathemati al model that des ribes this behavior. It is of
the form
a1 a2
V (r) = 12
− 6 (22)
r r
Obviously, V (r) has a minimum, say ǫ alled well depth. Let σ be the distan e at
whi h the potential vanishes alled hard sphere radius. Expressing a1 and a2 in terms
of ǫ and σ ,one gets
σ 6
σ 12
V (r) = 4ε − (23)
r r
Algorithm
1: Read Well depth ε and hard sphere radius σ and distan e in rement dr
2: for r = 0 to 3σ step dr do
3: va ← 4ε(σ/r)6
4: vr ← 4ε(σ/r)12
5: V ← va + vr
6: plot va,vr,V
7: end for
8: End
Program
from pylab import*
epsilon,sigma=input('Give the values of potential Well depth and hard sphere
r=linspa e(sigma,3*sigma,1000)
vrepulsive=4*epsilon*(sigma/r)**12
vattra tive=-4*epsilon*(sigma/r)**6
vtotal=vrepulsive+vattra tive
plot(r,vattra tive)
plot(r,vrepulsive)
plot(r,vtotal)
show()
Result
The following graph is obtained.
Lennard-Jones potential
200
150
100
50
potential
50
100
150
200
0.20 0.25 0.30 0.35 0.40 0.45 0.50 0.55 0.60 0.65
Distance
2.2 Two-slit photon interferen e 17
Aim
To plot the probability density for arrival of photons s attered by two slits at ea h
point on a s reen kept at a xed distan e from the line of slits and parallel to it.
slits
o
x
d/2
sour e o
d/2
o D
S reen
Prin iple
1
Consider a set of photons of identi al in all respe ts moving toward the line of slits.
At the slits they get s attered in dierent dire tions with dierent probabilities. The
onsequent state of the photons an be des ribed by a spheri al wave fun tion
~
eik.~r12
ψ(~r12 ) = (24)
r12
where ~r12 = ~r1 − ~r2 , k = 2π/λ is the wave ve tor and λ, the wavelength of the
photon. Equation 24 is a reasonably good estimate of the probability amplitude for
a free parti le to move from position ~r1 to position ~r2 in empty spa e. In gure, the
ontribution to probability amplitude from left path is given by
eikrAC
ψL (x) = (25)
rAC
eikrBC
ψR (x) = (26)
rBC
1 Ref:Chapter-3 , Volume-III,'Feynmann's Le tures on Physi s'
18 2 SIMULATION OF PHYSICAL PHENOMENA
P (x)of nding the photon at various points on the s reen is plotted against x for four
ases.
1. When only left slit is open,
1
PL (x) = |ψL (x)|2 = 2
(27)
rAC
Algorithm
1: De lare data type of all variables.
2: Read d and b as multiples of wavelength of the photon
3: p to 100 step 0.001 do
for x = −100
4: rAC ← pd2 + (x − b/2)2
5: rBC ← d2 + (x + b/2)2
1 1 2 cos k(rAC − rBC )
6: yLRI (x) ← 2 + 2 +
rAC rBC rAC .rBC
7: Plot yLRI (x)
8: end for
Program
from pylab import*
b=input("Distan e between the slits as multiple of wavelength(10 to 20) = ")
d=input("Distan e between line of slits and s reen as multiple of wavelength(
x=linspa e(-1000,1000,1000)
p=1/sqrt(d*d+(x-b/2)*(x-b/2))
q=1/sqrt(d*d+(x+b/2)*(x+b/2))
y=p*p+q*q+2*p*q* os(2*pi*(q-p)/(q*p))
2.3 Random Walk in One-Dimension 19
0.0000012
0.0000010
0.0000008
Intensity
0.0000006
0.0000004
0.0000002
0.0000000
1000 500 0 500 1000
Distance along the screen
Aim:
To establish the relation between the number of steps a Random walker takes and
his mean square displa ement.
Prin iple:
Random walk refers to a statisti al pro ess in whi h an obje t is assumed to move in
dire tions hosen at random through a xed distan e in xed intervals of time. It an
be used to explain physi al phenomena like diusion, Brownian motion, transport of
photons down the temperature gradient in stars et . Let us assume that ea h ollision
makes the parti le move either one step forward or one step ba kward and of length
unity (mean free path). As ollision is random, the probabilities for forward and
ba kward movements are equal and ex lusive (independent of ea h other).
At the beginning let the parti le be at x = 0. After one step of length unity let it
rea h some point x1 = ±1. Either the same parti le is brought ba k to x = 0 or a new
parti le starts from x = 0 and the above pro ess is repeated. As there is no preferred
dire tion, the mean value of x1 from all trials will be zero. That is, < x1 >= 0. But
20 2 SIMULATION OF PHYSICAL PHENOMENA
of unit length, the parti le has typi ally moved a distan e of 10 units from the origin,
and after 106 steps, typi ally a distan e 1000 units provided the number of trials are
large. In ontrast, if there is no randomness, then < xN > = N . This is a very
p
2
important result.
Algorithm
1: De lare oating point variables position x, sumX , sumX 2 , mean square deviation
msd and the probability required for forward step(+1 step) f having range 0 to
1. Integer variables are number of trials t and number of steps s
2: Set x ← 0, msd ← 0
3: Read t, s, f
4: Initialize random number generator fun tion rand if required.
5: sumX ← 0, sumX2 ← 0
6: for m = 1 to t do
7: n←0,x←0
8: for n = 1 to s do
9: p ← rand
10: if p ≥ f then
11: x← x+1
12: else
13: x← x−1
14: end if
15: end for
16: sumX ← sumX + x
17: sumX2 ← sumX2 + x2
18: end for
19: Mean displacement ← sumX/t
20: Mean square displacement ← sumX2/t
2.3 Random Walk in One-Dimension 21
Program
Result
45.2
45.0
Mean square displacement
44.8
44.6
44.4
44.2
44.0
Aim:
To establish the relation between the number of steps a Random walk takes and his
mean square displa ement.
Prin iple:
Random walk refers to a statisti al pro ess in whi h an obje t is assumed to move in
dire tions hosen at random through a xed distan e in xed intervals of time. It an
be used to explain physi al phenomena like diusion , Brownian motion, transport
of photons down the temperature gradient in stars et . Let us assume that ea h
ollision makes the parti le move either one step forward or one step ba kward and
of length unity mean free path). As ollision is random, the probabilities for motion
in all dire tions are equal and ex lusive (independent of ea h other).
After nth step of length unity in some dire tion θn , let it rea h some point (xn , yn)
so that (xn − xn−1 )2 + (yn − yn−1 )2 = 1, xn = xn−1 + cos θn , yn = yn−1 + sin θn .
The dire tion θn taken by the parti le is ompletely random. The value of θn in
ea h step is obtained by a random number generator fun tion. At the beginning let
the parti le be at (x0 , y0 ) = (0, 0). After the parti le ompletes the spe ied number
of steps, n, let d2 = x2n + yn2 be the square of net displa ement. Either the same
parti le is brought ba k to the origin or a new parti le starts from the origin and the
above pro ess is repeated. d2 is al ulated in ea h ase. Mean d2 =< d2 > over all
trials is al ulated in ea h ase. < x >=< y > must be zero as motion is isotropi .
But its mean square displa ement
2 Therandom motion under the a tion of a for e in some xed dire tion an be explored by
spe ifying a proportionately high probability for motion along the for e.
3 Sin e the two dire tions are equally likely, after a number of trial walks , the mean square
displa ement < x21 >=< y12 >
2.4 Random Walk in Two-Dimensions 23
Algorithm
Program
Result
24.0
23.5
Mean square displacement
23.0
22.5
22.0
21.5
Aim
To plot the traje tory of a parti le moving in a Coulomb eld and to determine angle
of dee tion as a fun tion of impa t parameter.
2.5 Motion in a Central For e Field:- Rutherford S attering 25
Prin iple
Rutherford's experiment is to measure the dee tion of a beam of α− parti les by
gold nu lii due to Coulomb repulsion. The ele trostati for e is given by
Ze.2e
F~ = r̂ (36)
4πǫ0 r 2
2ze2 x
ax = (37)
4mπǫ0 r 3
2ze2 y
ay = (38)
4mπǫ0 r 3
2ze2 d2 x d2 y
Putting c = , ax = 2 and ay = 2 one gets
4mπǫ0 dt dt
d2 x cx
= (39)
dt2 (x2 + y 2)3/2
d2 y cy
2
= 2 (40)
dt (x + y 2)3/2
The velo ity and position of every α−parti le at dierent instants of time are then
determined by solving the above dierential equations numeri ally. From gure, if
(x1 , y1 ) are asymptoti points , △ABC is isos eles. If θ is the angle of dee tion,
xn − x0
cot (θ/2) = (41)
yn − y0
Algorithm
1: Read the initial values of velo ities and positions of parti les in the beam, the
impa t parameter and the time step dt.
2: for b=0 to 20 step 1 do
3: while kyk is below a xed value yn do
4: Cal ulate ax and ay using formulae 40 and 2.5
5: Cal ulate x and y using 4th -order Runge-Kutta Method.
6: plot (x, y )
7: end while
8: Cal ulate cot (θ/2) and b/ cot (θ/2)
9: plot cot (θ/2) against b
10: end for
11: End program
26 2 SIMULATION OF PHYSICAL PHENOMENA
Program
from numpy import*
from pylab import*
=21.82743562;
dt=0.0001
x=zeros(10001,'float')
y=zeros(10001,'float')
b=linspa e(0,1,10)
otthetaby2=zeros(10,'float')
for j in range(10):
x[0℄,y[0℄,t,vx,vy=-5,b[j℄,0,10,0
for i in range(10000):
vx+=x[i℄* *dt/(x[i℄*x[i℄+y[i℄*y[i℄)**1.5
vy+=y[i℄* *dt/(x[i℄*x[i℄+y[i℄*y[i℄)**1.5
x[i+1℄=x[i℄+vx*dt
y[i+1℄=y[i℄+vy*dt
figure(1)
xlabel('x')
ylabel('y')
title("Path of alpha parti le")
plot(x,y)
otthetaby2[j℄=(x[i℄-x[0℄)/(y[i℄-y[0℄)
figure(2)
xlabel('impa t parameter b')
ylabel(' ot(theta/2)')
title("Relation between b and theta")
grid(True)
plot(b, otthetaby2)
show()
Result
2.6 Logisti equation
Logisti map
A map is a fun tion whi h relates the oordinates of a point Pn+1 in terms of those
of the previous point Pn . A map is always dis ret as it uses the previous value of
the dependent variable as the present value of independent variable. There is thus no
question of dierentiability for a map.
The logisti map is developed by Robert May in 1976 as a mathemati al model of
population growth whose generations do not overlap with a xed environment. It is
given by
where 0 < x < 1 and c > 1 A ontinuous form of the logisti map is the logisti
equation rst developed by P.F.Verllhurst in 1845.
f (x) = cx(1 − x) (43)
Mathemati al properties of
logisti map and equation
1. The roots of logisti equation 43 are obtained by setting f (x) = 0. They are
x=0 and x=1.
2.
df (x)
= c(1 − 2x) (44)
dx
Extremum o urs at df(x)/dx=0 whi h is, at x = 1/2. This is a maximum
be ause d2 f (x)/dx2 = −c whi h is negative. This point x=1/2 is alled the
riti al point of the fun tion possessing only a single maximum in a given in-
tervel ( 0 < x < 1) in this ase.
3. After some iterations of the map 42, it often onverges to some xed value alled
an 'attra tor'. Any further iteration of 42 will yield the same value. If x∗n is
su h a value,
x∗n = cx∗n (1 − x∗n ) (45)
x∗n = 1 − 1/c (46)
When c = 3 the attra tor bifur ates to two xed points x∗1 and x∗2 in su h a way
that
x∗2 = f (x∗1 )
x∗1 = f (x∗2 )
x∗2 = f [f (x∗2 )]
= c2 x∗2 (1 − x∗2 )[1 − cx∗2 (1 − x∗2 )]
This dimensionless number, alled Feigenbaum number, is a universal onstant for all
maps whi h takes the route of bifur ation to haos.
Program
from pylab import*
def f( , x): return * x * (1 - x)
i, f,x0,n,g =2.9,3.655, 0.1,50,1000
i, f=input("range of ontrol parameter = ")
s=( f- i)/1000.0
L ,Lx = [℄,[℄
for in arange( i, f, s):
x = x0
for i in range(g): x = f( , x)
p = 0
while p < n:
2.7 Simulation of Kepler's First and se ond Laws 29
x = f( , x)
L .append( )
Lx.append(x)
p += 1
plot(L , Lx, ".")
xlabel("Control Parameter")
ylabel("Population")
show()
Logistic Map
1.0
0.8
0.6
Population
0.4
0.2
Aim
Prin iple
Kepler's laws are a onsequen e of Newton's law of Gravitation.
GMm
F~ = r̂ (52)
r2
A eleration and its omponents are found as follows
r 2 = x2 + y 2 (53)
GM
~a = r̂ (54)
r2
GMx
ax = (55)
r3
GMy
ay = (56)
r3
vx = vx0 + ax dt (57)
vy = vy0 + ay dt (58)
x = x0 + vx dt (59)
y = y0 + vy dt (60)
We an express GM in terms of mean earth to sun distan e r = 1.496 × 1011 m=1
astronomi al unit(AU) and time in tropi al year 1y = 3.15569259747 × 107 s. As
earth's orbit is nearly ir ular (e entri ity=0.016), gravitational for e is ompletely
entripetal.
GMm
mrω 2 = (61)
r2
GM = 2 3
ω r (62)
4π 2 r 3
= (63)
T2
= 4π 2 (AU)3 /y 2 (64)
= 39.47841760(AU)3/y 2 (65)
First law states that the orbit is an ellipse with sun at one of the fo ii. An x-y plot
gives the shape of the orbit whi h an be seen to be an ellipse.
Se ond law states that areal velo ity is a onstant. If dA is the area swept by
radius ve tor ~r in time dt with an angular displa ement dθ, then
dA 1 2 dθ
= r (66)
dt 2 dt
1 2
= r ω
2
1
= rv (67)
2
1q 2
= (x + y 2 )(vx2 + vy2 ) (68)
2
A graph of t − dA/dt an be seen to be a straight line parallel to time axis.
2.7 Simulation of Kepler's First and se ond Laws 31
Algorithm
(x0 , y0 ) is a point on the orbit at time t
(x, , y) is point on the orbit at time t + dt
(vx , vy ) is velo ity at time t
(ax , ay ) is a eleration at time t.
GM = 39.47841760, a onstant
1: Read x0 and vy
2: y0 ← 0 and t ← 0
3: ⊲ Choose x-axis as the line joining sun and planet at t=0
4: vx0 ← 0
5:
6: for i=0 p
to k do
7: r ← q(x20 + y02)
8: v← (vx2 + vy2 )
9: ax ← −GMx0 /r 3
10: ay ← −GMy0 /r 3
11: vx ← ax dt + vx
12: vy ← ay dt + vy
13: x ← vx dt + x0
14: y ← vy dt + y0 ⊲ This plot is the path of the planet around sun
15: dA/dt ← 21 rv
16: t ← t + dt
17: if (y0 < 0 and y > 0) then break.
18: end if
19: end for
20: Plot y against x
21: Plot dA/dt against t
22: Stop
Program
from pylab import*
gm,k=39.4784176,10000
#gm=Gravitational onstant G.mass of sun M, a areal velo ity
x,y=zeros(k,'float'),zeros(k,'float')
t,a=zeros(k,'float'),zeros(k,'float')
#Choose x axis along the initial position of the planet and sun
# and velo ity along y-axis.
y[0℄,vx=0.0,0.0
x[0℄=input('Give initial distan e as multiple of mean sun-earth distan e Ro')
# Choose velo ity to be near to ir ular motion GMm/r^2=mv^2/r
print 'and velo ity of planet as multiple of Ro/year (<%f)'%(1.1*sqrt(gm/x[0℄))
vy=input(' ')
32 2 SIMULATION OF PHYSICAL PHENOMENA
dt=4*pi*x[0℄/(k*vy)
for i in range(k-1):
r=sqrt(x[i℄**2+y[i℄**2)
v=sqrt(vx**2+vy**2)
vx-=gm*x[i℄*dt/r**3
vy-=gm*y[i℄*dt/r**3
x[i+1℄=x[i℄+vx*dt
y[i+1℄=y[i℄+vy*dt
a[i℄=r*v/2
t[i+1℄=i*dt
if y[i℄<0 and y[i+1℄>0: break
figure(1)
title("Path of planet")
xlabel('x')
ylabel('y')
plot(x,y,'.')
figure(2)
title("Areal velo ity-time graph")
xlabel('Time')
ylabel('Areal velo ity')
plot(t,a,'.')
show()
1.5
4.0
3.5
1.0
3.0
0.5
Areal velocity
2.5
y
0.0
2.0
0.5
1.5
1.0
1.0
1.5
0.5
2.0
2.5 2.0 1.5 1.0 0.5 0.0 0.5 1.0 1.5 2.0
0.00.0 0.5 1.0 1.5 2.0 2.5 3.0
x Time
Aim
To write a omputer program in C language to simulate Kepler's Third Law and
exe ute it.
Prin iple
Kepler's laws are a onsequen e of Newton's law of Gravitation.
GMm
F~ = r̂ (69)
r2
2.8 Simulation of Kepler's Third Law 33
r 2 = x2 + y 2 (70)
GM
~a = r̂ (71)
r2
GMx
ax = (72)
r3
GMy
ay = (73)
r3
vx = vx0 + ax dt (74)
vy = vy0 + ay dt (75)
x = x0 + vx dt (76)
y = y0 + vy dt (77)
Expressing GM in terms of mean earth to sun distan e r = 1.496×1011 m=1 astronom-
i al unit(AU) and time in tropi al year 1y = 3.15569259747×107s, GM ≈ 39.4784176.
Also as earth's orbit is nearly ir ular (e entri ity=0.016), gravitational for e is om-
pletely entripetal.
GMm
mrω 2 = (78)
r2
GM = 2 3
ω r (79)
4π 2 r 3
= (80)
T2
= 4π 2 (AU)3 /y 2 (81)
= 39.47841760(AU)3/y 2 (82)
Third law states that period p and semi major axis a of the orbit are related as
p2 ∝ a3 .log p − log a graph is a straight line with positive slope.
Algorithm
(x0 , y0 ) ←Point on the orbit at time t
(x, , y) ←Point on the orbit at time t + dt
(vx0 , vy0 ) ←velo ity of the planet at time t
(vx , vy ) ←velo ity at time t + dt
(ax , ay ) ← a eleration at time t
p ← orbital period
r ← distan e between sun and planet
gm = 39.47841760, a onstant
Program
from pylab import*
def period(r0,v0):
gm,k=39.4784176,10000
x,y=zeros(k,'float'),zeros(k,'float')
t=0.0
y[0℄,vx=0.0,0.0
x[0℄,vy=r0,v0
dt=4*pi*x[0℄/(k*vy)
for i in range(k-1):
r=sqrt(x[i℄**2+y[i℄**2)
v=sqrt(vx**2+vy**2)
vx-=gm*x[i℄*dt/r**3
2.8 Simulation of Kepler's Third Law 35
vy-=gm*y[i℄*dt/r**3
x[i+1℄=x[i℄+vx*dt
y[i+1℄=y[i℄+vy*dt
t+=dt
if y[i℄<0 and y[i+1℄>0:break
if (max(y)-min(y))>(max(x)-min(x)):a=(max(y)-min(y))/2
else:a=(max(x)-min(x))/2
return t,a
z=linspa e(0.5,20,20)
w=sqrt(2*39.4784176/z)
p,m=zeros(20,'float'),zeros(20,'float')
for j in range(20): p[j℄,m[j℄,=period(z[j℄,w[j℄)
lm,lp=3*log(m),2*log(p)
title("Semimajor axis-period graph")
xlabel('3 log(r)')
ylabel('2 log(T)')
plot(lm,lp)
show()
6
2 log(T)
2
4 2 0 2 4 6 8 10
3 log(r)
36 2 SIMULATION OF PHYSICAL PHENOMENA
37