0% found this document useful (0 votes)
117 views72 pages

CSR KC: Lecture 8: Python For Teaching Physics-I

This document discusses using Python for teaching physics concepts. It begins with an overview of using Python as a tool for numerical methods like root finding, numerical integration, differentiation, and special functions commonly used in physics. It then discusses applications in quantum mechanics, including eigen-analysis, solving transcendental equations for quantum well potentials, and modeling scattering and quantum harmonic oscillator problems. The document is a lecture outline intended to introduce using Python for teaching fundamental physics concepts.

Uploaded by

deepak_senior
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views72 pages

CSR KC: Lecture 8: Python For Teaching Physics-I

This document discusses using Python for teaching physics concepts. It begins with an overview of using Python as a tool for numerical methods like root finding, numerical integration, differentiation, and special functions commonly used in physics. It then discusses applications in quantum mechanics, including eigen-analysis, solving transcendental equations for quantum well potentials, and modeling scattering and quantum harmonic oscillator problems. The document is a lecture outline intended to introduce using Python for teaching fundamental physics concepts.

Uploaded by

deepak_senior
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

July 2020

Lecture 8: Python For Teaching Physics-I

Sandeep S Ghugre UGC DAE CSR,KC

Note : This lecture attempts to use the Open Source tools in elucidating some of the

KC
fundamental aspects (concepts) routinely encountered in UG & PG Physics courses.

Disclaimer : These notes have not been subjected to the usual scrutiny reserved for formal
publications. They may be distributed outside the intended audience only with the per-
mission of the author. The material has been developed following the discussions with our
colleagues, during the workshops that have been conducted in collaboration with

ˆ
SR
Department of Physics, Asutosh College, Kolkata : November 7th − 8th

Department of Physics & Computer Science, Bethune College, Kolkata, July


2018

R. P. Gogate College of Arts & Science, Ratnagiri, December 18th − 19th


, 2017

19th −20th

2018

ˆ
AE
S. H. Kelkar College, Devgad, December 22nd − 23rd 2018

ˆ Department of Physics, Government Holkar Science College, Indore, September 17th − 18th
2019
CD

ˆ Department of Physics, R.D & S.H National College, Mumbai, February 6th − 7th
2020

ˆ Department of Physics, Victoria Institution (College), Kolkata, July 6th − 10th 2020

The help and support received from Ms Kathakali Biswas, Victorial Institution (College),
UG

Kolkata and Dr Rajamani Raghunathan, UGC DAE CSR, Indore Centre in preparing this
manuscript is greatfully acknowledged.

Contents

8.1 Swiss Knife for Numerical Methods 8-4


0
Email : [email protected] & [email protected]

8-1
8-2 Lecture 8: Python For Teaching Physics-I

8.1.1 Root Finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4

8.1.1.1 Graphical Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4

8.1.1.2 Roots of an equation using scipy . . . . . . . . . . . . . . . . . . . 8-7

8.1.1.3 Bisection Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7

8.1.1.4 Newton Rapshon Method . . . . . . . . . . . . . . . . . . . . . . . 8-11

8.1.2 Numerical Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-16

8.1.2.1 Trapezoidal Method . . . . . . . . . . . . . . . . . . . . . . . . . . 8-17

KC
8.1.2.2 Simpson's Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-18

8.1.2.3 Improper Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-20

8.1.3 Numerical Dierentiation : Finite Dierences . . . . . . . . . . . . . . . . 8-21

8.1.4

8.1.5
CBessel Functions

8.1.5.1

8.1.5.2

8.1.5.3
SR
Special Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

First Order Bessel Function . . . . . . . . . . . . . . . . . . . . . .

Zeros of Bessel Function . . . . . . . . . . . . . . . . . . . . . . . .

Recursive Relations for Bessel Function . . . . . . . . . . . . . . .


8-22

8-24

8-25

8-25

8-26
AE
8.1.6 Legendre's Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-28

8.1.6.1 Recurrence Relationship for Legendre Polynomials . . . . . . . . . 8-29

8.1.6.2 Orthogonality of Legendre Polynomial . . . . . . . . . . . . . . . . 8-30


CD

8.1.7 Spherical Harmonics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-31

8.1.8 Sine & Cosine Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-35

8.1.9 Transcendental equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-37

8.1.10 Fourier Transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-41


UG

8.1.11 Dirac Delta Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44

8.2 Quantum Mechanics 8-46


8.2.1 Eigen-analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-46

8.2.1.1 Eigen Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-46

8.2.1.2 Eigen Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-48

8.2.2 Transcendental Equations for Finite Square Well Potential . . . . . . . . . 8-49


Lecture 8: Python For Teaching Physics-I 8-3

8.2.3 Scattering from Step Potential . . . . . . . . . . . . . . . . . . . . . . . . 8-56

8.2.4 Scattering from Potential Well . . . . . . . . . . . . . . . . . . . . . . . . 8-58

8.2.5 Central Potential : Hydrogen Atom. . . . . . . . . . . . . . . . . . . . . . 8-60

8.2.6 Symmetric Potential: Harmonic Oscillator . . . . . . . . . . . . . . . . . . 8-64

8.2.7 Wave Packets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-66

KC
C SR
AE
CD
UG
8-4 Lecture 8: Python For Teaching Physics-I

8.1 Swiss Knife for Numerical Methods

8.1.1 Root Finding

We shall now consider a task which is commonly encountered in all branches of Science, viz.
solving equations numerically. We know that all equations are born with both right and left
hand sides. However, we traditionally move all the terms to one side, say the left, so as to
leave us with

KC
f (x) = 0

as roots of the equation


f (x).
C f (x) = 0.
SR
ie we determine the value(s) of x, for which f (x) = 0. The solutions (values of x), are known
They are also referred to as the zeros of the function

In general, an equation may have any number of roots, or no roots at all.

For example, we know that the equation sin(x) − x = 0, has only one root, at x = 0, whereas
tan(x) − x = 0 roots, at x = 0, ±4.493, ±7.725, · · · .
AE
has innite number of
CD

8.1.1.1 Graphical Method


Now, we can nd the real roots graphically , such that the real number x = a, is a root
of the polynomial f (x), if and only if, f (a) = 0 , ie the x-intercepts of the graph of f (x),
UG

would correspond to the real roots of the function.

Now suppose we wish to nd the root of f (x) = x3 − 10x2 + 5 = 0, in the interval [0.6, 0.8],
then we make a plot of the function for 0.6 ≤ x ≤ 0.8, and the x-intercept(s) would give us
the root, zeros of the function.

The Python code prgs:nd_roots_graph.py to achieve the above is


Lecture 8: Python For Teaching Physics-I 8-5

Root nding by graphical method

1 import numpy as np
2 import matplotlib . pyplot as plt
3
4 x=np . l i n s p a c e ( 0 . 6 , 0 . 8 , 1 0 0 )
5 y=x ** 3 - 1 0 * x ** 2+5
6
7 plt . plot (x , y)
8 p l t . t i t l e ( ` Root ( s ) of $ f ( x)=x ^ 3 - 1 0 x^2+5 =0$ ' )

KC
9 plt . grid ()
10 p l t . show ( )

As seen from Fig. 8.1, the graph has 0.7345, as the x-intercept, which corresponds to the
root of the function.

C SR
AE
CD
UG

Figure 8.1: Graphical method to determine the roots.

Exercise 8.1 Use the graphical approach prgs:nd_roots_drag.py to determine the drag co-
ecient needed for a parachutist of mass m = 568.1 kg to have a velocity of 40 m/s after free
falling for time t = 10 s. The relevant equation is
 
g·m −(c/m)t
f (c) = 1−e −v
c
8-6 Lecture 8: Python For Teaching Physics-I

Solution:

Root nding by graphical method

1 import numpy as np
2 import matplotlib . pyplot as plt
3 c=np . a r a n g e ( 1 , 3 0 , 1 )
4 m= 6 8 . 1
5 v =40.0

KC
6 g = 9.81
7 t =10
8
9 y = ( g *m) / c * ( 1 - np . e x p ( - ( c /m) * t ) ) - v
10
11 plt . plot (c , y ,"b- -")
12
13
14
15
16
plt . xlabel ( 'c ')
plt . ylabel ( ' $f ( c )$ ' )
pl t . t i t l e ( ' Graphical
plt . grid ()
C
p l t . show ( )
approach for
SR
determining the roots ' )
AE
CD
UG

Figure 8.2: Graphical method to determine the roots.


Lecture 8: Python For Teaching Physics-I 8-7

8.1.1.2 Roots of an equation using scipy


The package scipy has a library optimize which has a function fsolve, which attempts to nd

the roots of a function. The arguments for the function are funx,x0 where func is the
desired function whose roots are to be determined and x0 is the starting estimate for the
roots of the function (f unc(x) = 0).
Further, we can compare the results, by using the isclose function from numpy. The
arguments for this function are a,b , where it returns a boolean array where the two arrays
a&b are compared element-wise within a given tolerance, which is set to a very low value.

KC
The Python code below prgs:nd_roots_scipy_0.py attempts to nd the root of the function
f (x) = x3 − 10x2 + 5 = 0, within the interval [0.6, 0.8], using the fsolve function.

1
2
3
4
5
6
import
import
from

def
C numpy as

scipy . optimize

func ( x ) :
return
np
matplotlib . pyplot
import

x ** 3 - 1 0 * x ** 2+5
as
SR
Root nding by scipy.optimize.fsolve

plt
fsolve
AE
7
8 x0= f s o l v e ( f u n c , 0 . 8 )
9 r e s u l t =np . i s c l o s e ( f u n c ( x0 ) , [0.00])
10
CD

11 print ( x0 )
12 print result

The output of this program is the root of the given equation, and the comparison of f (root)
with 0 should be TRUE , if we have the correct root.
UG

8.1.1.3 Bisection Method


We know that a root is bracketed in the interval [a, b], if f (a) and f (b) have opposite sign,
ie the function swings to the opposite polarity, and thus crosses zero in the given interval.
Technically, this is stated by the intermediate value theorem, as if the function is continuous,
1
then atleast one root must lie within the given / chosen interval.

1
Ocourse this have a caveat, as it does not include discontinuities
8-8 Lecture 8: Python For Teaching Physics-I

After having conrmed that the root of the f (x) = 0 has been bracketed in the interval
[x1 , x2 ], several numerical prescriptions are available to rene it. One such method happens
to be the bisection method.

If there is a root in the interval [x1 , x2 ], then in this interval the function, is known to pass
through zero, and hence, we have f (x1 ) · f (x2 ) < 0.
 
In order to narrow down the interval, we compute f (xmid−point ) = f (x3 ) = 1/2 x1 + x2 .
Following the bisection of the interval, we compute f (x3 ), and if f (x2 ) · f (x3 ) < 0, then we
know that the root must be within the interval [x2 , x3 ], and we know restrict our search in

KC
this interval, by replacing original bound x1 , with x3 . Else we know that the root is in the
interval [x1 , x3 ], then we have to replace x2 , by x3 .

Either way the original interval is halved, and we continue to chop the interval, until, the
interval has been reduced to a value less than or equal to the desired tolerance , so that

|x2 − x1 | ≤ 

Hence, after
SR
Since, after each iterations, the bound containing the root

after the next iteration, it will be bracketed within an interval of size


C
n+1 =
n
2
decreases by a factor of two.
n iterations, the root would be bracketed within an interval of size n , such that
AE
We can compute the number of iterations required to achieve the desired accuracy  from
the relation
ln|∆x|/
n =
ln2
CD

Exercise 8.2 Use the bisection method to nd the root of f (x) = x 3
− 2x − 5 = 0 that is
know to lie in the interval [2, 3]

Solution:
Hence, we know that the root of the equation is in the close vicinity of 2.094, to an accuracy
UG

of second decimal point.

Exercise 8.3 Use the bisection method to nd the root of f (x) = x 3
− 10x2 + 5 = 0, that
lies in the interval [06, 0.8]

Solution: The nal result x = 0.73458 is the desired result.

Now, let us attempt to nd the roots of the above function, using the Bisection Method,
in Python. The code below prgs_2:bisection_2.py could be used to implement this. The
results are also cross checked using the graphical method, as well as the scipy module.
Lecture 8: Python For Teaching Physics-I 8-9

Table 8.1: Root of f (x) = x3 − 2x − 5 = 0

x f (x) Interval
2 -1 -
3 16 [2,3]
(2+3) 2 ⁄ = 2.5 5.625 [2,2.5]
(2+2.5) 2
⁄ =2.25 1.890 [2, 2.25]
(2+2.25) 2
⁄ = 2.125 0.345 [ 2, 2.125]
(2+2.125)⁄2 = 2.0625 -0.351 [2.0625, 2.125]

KC
(2.0625+2.1250) 2 ⁄ = 2.094 0.006 -

C Table 8.2: Root of

x
0.6
SR f (x) = x3 − 10x2 + 5 = 0

f (x)
1.616
Interval
-
AE
0.8 -0.888 [0.6,0.8]
(0.6+0.8) 2
⁄ = 0.7 0.443 [0.7,0.8]
(0.8+0.7) 2
⁄ =0.75 -.203 [0.7,0.75]
(0.7+0.75) 2
⁄ = 0.725 0.125 [ 0.725, 0.75]
CD

(0.725+0.75) 2⁄ = 0.7375 -0.038 [0.725, 0.7375]


(0.725+0.7375)⁄2 = 0.73125 0.044 [0.73125, 0.7375]
(0.73125+0.7375)⁄2 = 0.73438 0.003 [0.73438, 0.7375]
(0.73438+0.7375)⁄2 = 0.73594 -0.017 [0.73438, 0.73594]
(0.73438+0.73594)⁄2 = 0.73516 -0.007 [0.73438, 0.73516]
(0.73438+0.73516)⁄2 = 0.73477 -0.002 [0.73438, 0.73477]
UG

(0.73438+0.73477)⁄2 = 0.73458 0.00 -


8-10 Lecture 8: Python For Teaching Physics-I

Root nding by Bisection Method

1 #r o o t finding using BISECTION METHOD


2
3 import numpy as np
4 import matplotlib . pyplot as plt
5 from scipy . optimize import fsolve
6 def f (x ): #d e f i n i n g the function
7 return x ** 3 - 1 0 * x ** 2 + 5
8 def bisection (a ,b , tol ):

KC
9 x l=a #f i r s t guess value
10 xh=b #s e c o n d guess value
11 print " xl xh c f ( c )"
12 while np . a b s ( x l - xh)>= t o l :
13 c =( x l+xh ) / 2 . 0
14 print "%.5 f %.5 f %.5 f %.5 f " %( x l , xh , c , f ( c ) )
15
16
17
18
19
20
if

elif
C
else :
np . a b s ( f ( c ))<= t o l :
break
( f ( c )* f ( x l )) <0:
xh=c

x l=c
SR
21 return c
AE
22
23 a , b , t o l =i n p u t ( " e n t e r the value of a ,b , tolerance :")
24 if ( f ( a )* f (b ) ) > 0:
25 p r i n t (" root finding using these guess values is not p o s s i b l e ")
CD

26 elif np . a b s ( f ( a ) ) <= tol :


27 p r i n t (" the first given guess value is the root ")
28 elif np . a b s ( f ( b ) ) <= tol :
29 p r i n t (" the second given guess value is the root ")
30 else :
31 r o o t= b i s e c t i o n ( a , b , t o l )
UG

32 print (" the value of root i s ") , root


33
34 a r o o t= f s o l v e ( f , a )
35 p r i n t (" the value of root using fsolve i s ") , aroot [ 0 ]
36 r e s u l t =np . i s c l o s e ( r o o t , aroot )
37 if ( r e s u l t ==True ) :
38 print ( " The computed root agrees with the analytical value ")
39 x=np . l i n s p a c e ( - 0 , 4 , 1 0 0 )
40 p l t . p l o t ( root , f ( root ) ," r *" , m a r k e r s i z e =12 , l a b e l = ' Root ' )
41 plt . plot (x , f (x )) #p l o t t i n g the function to visualize the roots
42 p l t . t i t l e ( ' Roots by Bisection Method ' )
43 plt . xlabel ( 'x ')
44 plt . ylabel ( ' $f (x)$ ' )
45 plt . legend ()
46 plt . grid ()
47 p l t . show ( )
Lecture 8: Python For Teaching Physics-I 8-11

The results are plotted in Fig. 8.3.

KC
C Figure 8.3:
SR
Graphical method to determine the roots.
AE
8.1.1.4 Newton Rapshon Method
This method is perhaps the most celebrated method to nd the roots of a given equation.
However, the down side of this method is that it requires the evaluation of both the function
CD

and it's derivative at arbitrary points x.


The method can be derived from the Taylor Series expansion of f (x) about x, ie.

f (xi+1 ) = f (xi ) + f 0 (xi )(xi+1 − xi ) + O(xi+1 − xi )2


UG

Now, if xi+1 , is a root of the given equation, then f (x) = 0, hence we have

0 = f (xi ) + f 0 (xi )(xi+1 − xi ) + O(xi+1 − xi )2

Assuming, that the dierence δ = xi+1 −xi , is very small, we can ignore the term O(xi+1 −xi )2
and we have, the Newton-Raphson method, as

f (xi )
xi+1 = xi −
f 0 (xi )
8-12 Lecture 8: Python For Teaching Physics-I

The major advantage is that this method converges quadratically, (the error is the square
of the error in the previous step).

If x is the true value of the root, then the error in xi , is E = x − xi , and the error in xi+1
computed from this value is

KC
f 00 (xi ) 2
Ei+1 = − E
2f 0 (xi ) i

C SR
AE
Hence, provided x is close to the root, the number of signicant gures is doubled in every
iteration.
CD
UG

Exercise 8.4 A root of f (x) = x 3


− 2x − 5 = 0, lies close to x = 2. Compute this root with
Newton-Raphson method.
Lecture 8: Python For Teaching Physics-I 8-13

Solution:
f (x) = x3 − 2x − 5
f 0 (x) = 3x2 − 2
f (x)
x ←− x − 0
f
x3 − 2x2 − 5
= x−
3x2 − 2
3x − 2x − x3 + 2x + 5
3
=

KC
3x2 − 2
3
2x + 5
=
3x2 − 2
For x = 3

2(3)3 + 5
x ←−

SR
3(3)2 − 2
= 2.36
for x = 2.36

2(2.36)3 + 5
C x ←−
3(2.36)2 − 2
= 2.13
For x = 2.13
AE
2(2.13)3 + 5
x ←−
3(2.13)2 − 2
= 2.095
CD

For x = 2.095

2(2.095)3 + 5
x ←−
3(2.095)2 − 2
= 2.094
UG

Thus in a spate of few iterations we have been able to achieve an accuracy upto second
decimal place.

Exercise 8.5 A root of f (x) = x 3


− 10x2 + 5 = 0 lies close to x = 0.7. Compute this root
with the Newton Rapshon method.

Solution: 0.73460

The code presented below (prgs:newton_raphson.py), attempts to obtain the roots of the
equation by Newton Raphson Method .
8-14 Lecture 8: Python For Teaching Physics-I

KC
SR
C
AE
CD
UG
Lecture 8: Python For Teaching Physics-I 8-15

Root nding by Newton Rapshon Method

1 #r o o t finding u s i n g NEWTON RAPHSON METHOD


2 import numpy as np
3 import matplotlib . pyplot as plt
4 from scipy . optimize import fsolve
5 def f (x ): #d e f i n i n g f (x)
6 return x ** 3+x ** 2 - 3 * x - 3
7 def g(x ): #d e f i n i n g f '( x)
8 return 3 * x ** 2 - 2 * x - 5

KC
9 def newton_rapson ( a , t o l ) :
10 x0=a #g u e s s value
11 c h e c k =1
12 h=f ( x0 ) / ( g ( x0 ) * 1 . 0 )
13 i f ( np . a b s ( g ( x0 ))<= t o l ) : # since when f ' ( x )=0 , the calculatio
14 print " cannot proceed to find root "
15
16
17
18
19
20
C while
return

x0 =(x0 - h )
False
np . a b s ( h)>= t o l :

i f ( np . a b s ( g ( x0 ))<= t o l ) :
print
return
" cannot
False
SRproceed
# since
to find
when f ' ( x )=0
root "
, the calculatio

21 h=f ( x0 ) / ( g ( x0 ) * 1 . 0 )
AE
22 if np . a b s ( h)<= t o l :
23 return x0
24
25 a , t o l =i n p u t (" enter the value of a and tolerance :")
CD

26
27 if np . a b s ( f ( a))<= t o l :
28 print " the first given guess value is the root " ,a
29 else :
30 r o o t=n e w t o n _ r a p s o n ( a , t o l )
31 i f ( r o o t != F a l s e ) :
UG

32 print " the value of root is " , root


33
34 a r o o t= f s o l v e ( f , a )
35 print ' the actual root is ' , aroot [ 0 ]
36 x=np . l i n s p a c e ( - 2 , 2 , 1 0 0 )
37 plt . plot (x , f (x ))
38 p l t . x l a b e l ( ' $x$ ' )
39 plt . ylabel ( ' $f (x)$ ' )
40 p l t . t i t l e ( ' Root finding by Newton Raphson Method ' )
41 p l t . ylim ( - 6 . 0 , 6 . 0 )
42 plt . grid ()
43 p l t . show ( )
8-16 Lecture 8: Python For Teaching Physics-I

The results are plotted in Fig. 8.4.

KC
C
Figure 8.4:
SR
Conrmation of the Roots obtained by Bisection Method.
AE

8.1.2 Numerical Integration


CD

Mathematically, the integral of a function, f (x), with respect to the independent variable
x, evaluated between the limits x=a to x = b,is represented as
Z b
I = f (x)dx
a
UG

The function f (x), is referred to as the integrand. Intuitive approach, would be to plot the
given function on a grid plot, and count the number of boxes so as to approximate the area.
At the cost of ner grid (increased computational eort), we can have a closer estimate to
the expected result.

The Newton-Cotes formulas are the most preferred choice for performing numerical inte-
gration. They are based on the strategy of replacing the function, with an approximation
function, such as a convenient polynomial, which is easy to integrate.

The Trapezoidal rule is one of the simplest methods to carry out the numerical integration.
Lecture 8: Python For Teaching Physics-I 8-17

8.1.2.1 Trapezoidal Method


Rb
In general, given a function f (x), then the denite integral
a
f (x)dx, represents the area
under the curve represented by the function, between two points a & b.
Numerically, this is achieved, by the trapezoid rule , which kind of divides the entire curve
in consideration, into trapezoids, connecting the points

(xi−1 , 0), (xi , 0), (xi−1 , f (xi−1 )), (xi , f (xi ))

KC
The areas of the individual trapezoid (which happens to be the sum of triangle and a rect-
angle) for each sub-interval [xi−1 , xi ] are summed up to yield the value for the nite integral.

SR
Z
1
f (x) = (xi − xi−1 )f (xi−1 ) + (xi − xi−1 )(f (xi ) − f (xi−1 )
a 2
1
= (f (xi ) + f (xi−1 ))(xi − xi−1 )
2
C
At times, the area of the rectangle is calculated using the mid-point as the height
AE
b
(b − a)
Z
f (x) = [f (x¯1 ) + f (x¯2 ) + · · · + f (x¯n )]
a N
1
where x¯n = (xn−1 + xn )
2
CD

Rb
Hence, to approximate
a
f (x)dx with n of these trapezoids, we have

Z b  n n 
1 X X
f (x)dx = f (xi − 1)∆x + f (xi )∆x
a 2 i=1 i=1
UG

 
∆x
= f (x0 ) + f (x1 ) + f (x1 ) + f (x2 ) + f (x2 ) + · · · + f (xn−1 ) + f (xn )
2
 
∆x
= f (x0 ) + 2f (x1 ) + 2f (x2 ) + · · · + 2f (xn−1 ) + f (xn )
2
where

(b − a)
∆x =
n

The Python code (prgs:int_trap_1.py) to achieve the above is


8-18 Lecture 8: Python For Teaching Physics-I

Numerical Integration by Trapezoidal Rule

1 import numpy as np
2
3 def t r a p z ( f , a , b , N= 5 0 ) :
4 x=np . l i n s p a c e ( a , b , N+1)
5 y=f ( x )
6 y_right = y [ 1 : ]
7 y_left = y [ : - 1 ]

KC
8 dx = f l o a t ( ( b - a ) /N)
9 T = ( dx / 2 . 0 ) * np . sum ( y _ r i g h t + y_left )
10 return T
11
12 def m i d _ t r a p z (N, a , b ) :
13 def f (x ):
14
15
16
17
18
19
value = 0
return

value2 = 0
for
C
n in
np . s i n ( x )

r a n g e ( 1 , (N+ 1 ) ) :
SR
v a l u e = v a l u e + f ( a +(( n - ( 1 . 0 / 2 . 0 ) ) * ( ( b - a ) /N ) ) )
20 value = value
AE
21 v a l u e 2 = ( ( b - a ) /N) * v a l u e
22 return value2
23
24 r e s u l t _ 1 = t r a p z ( np . s i n , 0 , ( np . p i / 2 . 0 ) , 1 0 0 )
CD

25 r e s u l t _ 2 = m i d _ t r a p z ( 1 0 0 , 0 , ( np . p i / 2 . 0 ) )
26
27 y2 = np . l i n s p a c e ( 0 , ( np . p i / 2 . 0 ) , 2 5 7 )
28 r e s u l t _ 3 = np . t r a p z ( np . s i n ( y2 ) , y2 )
29 print result_1 , result_2 , result_3
UG

The above code has two f unctions viz., trapz and mid_trapz, based on the methods dis-
cussed above. The code also calculates the integral using the inbuilt trapz function in
numpy .

8.1.2.2 Simpson's Method


Simpson's Rule is a numerical method for performing integration, which is based on the fact
that given three points, we can t a quadratic through those points ie, there is a three-point
Lecture 8: Python For Teaching Physics-I 8-19

formula exact up to polynomial of degree 2.

It states that

Z x3  
1 4 1
f (x)dx = h f1 + f2 + f3

KC
x1 3 3 3

SR
This method has the distinct advantage over the Trapezoidal method,
degree of polynomial which is used to approximate the interval.
with respect to the
Without going into the
details, we know that the three-point formula is exact for polynomials up to and including
C
degree 3, ie 3
, f (x) = x .

The scipy.integrate sub-package, contains functions to carry out numerical evaluation of


the denite integrals, using various methodology such as Simpson's rule (simps), Romberg
AE
method (romb), to name a few.
The scipy.integrate.simps function would require the following arguements y,x , wherein the
function y(x) is integrated along the given axis.
CD

The code below prgs_2:trap_simpson.py, attempts the integration using explicitly the Trape-
zoidal Method, as well as the built-in function, for Simpson's rule, in the scipy.integrate
package.
UG
8-20 Lecture 8: Python For Teaching Physics-I

Numerical Integration by Simpson's Rule using scipy

1 #INTEGRATION METHOD u s i n g SIMPSON METHOD


2 import numpy as np
3 import matplotlib . pyplot as plt
4 import scipy . integrate as spi
5
6 def f (x ):
7 return 1.0/x
8

KC
9 def trapezoidal ( f , a ,b, tol ):
10 N=1
11 h=(b - a ) / (N * 1 . 0 )
12 S_new=h / 3 . 0 * ( f (a) + f (b))
13 while True :
14 S_old=S_new
15
16
17
18
19
20
N=N* 1 0
h=(b - a ) / (N * 1 . 0 )
x=np . l i n s p a c e ( a , b , N+1)
y=f ( x )
C
S_new=h / 3 . 0
i f ( a b s ( S_new
*
-
SR
np . sum ( y [ 0 : - 1 : 2 ]
S_old)<= t o l ) :
+ 4* y [ 1 : : 2 ] + y[2::2])

21 break
AE
22 I=s p i . s i m p s ( y , x )
23 return S_new , I , N
24
25
CD

26 a , b , t o l =i n p u t ( " e n t e r the lower and upper limit for integration and also toller
27 S , I , n=t r a p e z o i d a l ( f , a , b , t o l )
28 print " using trapezoidal method for integration :" ,S
29 print " using trapezoidal method for integration using scipy :" , I
30
31 #OUTPUT
UG

32 #'''
33 #e n t e r the limits for integration and also tollerence limit : 1 ,2 ,0.0001
34 #u s i n g trapezoidal method for integration : 0.6931471808723673
35 #u s i n g trapezoidal method for integration using scipy : 0.6931471808723672

8.1.2.3 Improper Integrals


We dene an integral R f (x)
a
b
as improper , if a or b is innite or f is undened, at a or b.
Lecture 8: Python For Teaching Physics-I 8-21

The Trapezoidal and Simpson's methods use the value of the integrand at the endpoints
of the domain of integration. For improper integrals, the function is not dened at these
points, hence rendering these methods ineective. The Gauss-Legendre method, which only
uses interior points , is better suited to numerically solve improper integrals.

The scipy.integrate.quad(f,a,b) computes the integral of the given function from a to b.


The code below (prgs_2:improper_integral_1.py)presents the methodology.

KC
Numerical Integration of improper integrals

1 #IMPROPER INTEGRATION EXAMPLE- 1


2 #Code f r o m Ms K B i s w a s
3 import numpy as np
4 import scipy
5 from scipy . integrate import quad #f o r integration using Gaussian Quad
6
7
8
9
10
11
import

F=lambda

print
C matplotlib . pyplot

" the
x: np . e x p ( - x )
I=quad ( F , 0 , np . i n f )

value of the
*
as

SR
plt

x ** 4

integration i s =" , I [ 0 ]
AE
Use the above code, to show that
Z 1
1
√ dx = 2
x
Z0 ∞
CD

1
dt = 1
1 t2

8.1.3 Numerical Dierentiation : Finite Dierences


UG

Many a times it is required to compute the derivative of a function, which can be dened
as

0 y(x + h) − y(x)
y =
h
0 yi+1 − yi
y =
xi+1 − xi

Where we have discretized, the function y(x), on an evenly spaced set of points x0 , x1 · · · xi
to obtain yi , yi+1 , · · · , yn .
8-22 Lecture 8: Python For Teaching Physics-I

This algorithm has been implemented in the following Python Code (prgs:dierentiate.py),
and the results are depicted in Fig.8.5.

Numerical Integration by Finite Dierences

1 import numpy as np
2 from matplotlib import pyplot as plt

KC
3
4 def nderiv (y , x ) :
5 " Finite difference derivative of the function f"
6 n = len (y)
7 d = np . z e r o s ( n , ' d ' ) # a s s u m e double
8 # Use centered differences for the interior points , one - s i d e d differences
9
10
11
12
13
14
15
for

d[0]
d[n-1]
return
i
d[ i ]
C in range (1 , n - 1 ) :

= (y [1] - y [0])/( x [1] - x [ 0 ] )


SR
= ( y [ i +1] - y [ i - 1 ] ) / ( x [ i +1] - x [ i - 1 ] )

= (y [n -1] - y [n -2])/( x [n -1] - x [n -2])


d

x = np . l i n s p a c e ( 0 , 2 * ( np . p i ) )
AE
16 d s i n = n d e r i v ( np . s i n ( x ) , x )
17 p l t . p l o t (x , dsin , ' r * ' , l a b e l =' n u m e r i c a l ')
18 p l t . p l o t ( x , np . c o s ( x ) , l a b e l = ' a n a l y t i c a l ' )
19 plt . t i t l e ( ' Derivative of sin (x) obtained numerically and analytically ')
20 plt . legend ()
CD

21 p l t . show ( )
UG

8.1.4 Special Functions


The Scipy module has several important mathematical functions which are routinely re-
quired in various branches of Physics, such as Bessel functions, Legendre Polynomials to
name a few. The Code below (prgs:special_functions.py) attempts to obtain a plot of these
functions, and the results are presented in Fig. 8.6.
Lecture 8: Python For Teaching Physics-I 8-23

KC
sin(x)

SR
Figure 8.5: Comparison of derivative of numerically and analytically.This code has
been adapted from http://csabai.web.elte.hu/http/szamSzimMsc/CrashCourse.html
C
Special Functions

1 from scipy . special import a i r y , jn , eval_chebyt , e v a l _ l e g e n d r e


AE
2 from matplotlib import pyplot as plt
3 import numpy as np
4
5 plt . subplot (2 ,2 ,1)
CD

6 x = np . l i n s p a c e ( - 1 , 1 )
7 Ai , Aip , Bi , Bip = a i r y ( x )
8 p l t . p l o t ( x , Ai )
9 p l t . p l o t ( x , Aip )
10 p l t . p l o t ( x , Bi )
11 p l t . p l o t ( x , Bip )
UG

12 p l t . t i t l e (" Airy f u n c t i o n s ")


13
14 plt . subplot (2 ,2 ,2)
15 x = np . l i n s p a c e ( 0 , 1 0 )
16 for i in range ( 4 ) :
17 plt . plot (x , jn ( i , x ))
18 p l t . t i t l e (" Bessel f u n c t i o n s ")
19
20 plt . subplot (2 ,2 ,3)
21 x = np . l i n s p a c e ( - 1 , 1 )
22 for i in range ( 6 ) :
23 p l t . p l o t ( x , eval_chebyt ( i , x ) )
24 p l t . t i t l e ( " C h e b ys h e v polynomials of the first kind ")
25
26 plt . subplot (2 ,2 ,4)
27 x = np . l i n s p a c e ( - 1 , 1 )
28 for i in range ( 6 ) :
29 plt . plot (x , eval_legendre ( i , x ))
8-24 Lecture 8: Python For Teaching Physics-I

KC
Figure 8.6:
C
.Important Mathematical Functions.
SR
http://csabai.web.elte.hu/http/szamSzimMsc/CrashCourse.html
This code has been adapted from
AE

8.1.5 Bessel Functions


Bessel functions the standard form of the solutions to Bessel's dierential equation,
CD

d2 y dy
x2 2
+ x + (x2 − ν 2 )y = 0
dx dx

The solution to the above Bessel's equation yields Bessel functions, of the rst and second
UG

kind as

y = AJν (x) + BYν (x)


where A and B are arbitrary constants

Jν (x) : Bessel function of rst kind


Yν (x) : Bessel function of second kind
ν = 0, 1, 2, 3, .....integer order

Bessel functions are usually presented in the form of integer order, in principle they are
dened for all real values −∞ < ν < ∞.
Lecture 8: Python For Teaching Physics-I 8-25

The Hankel function of Bessel function of the third kind, for x > 0, can be written as

Hν(1) (x) = Jν (x) + iYν (x)


Hν(2) (x) = Jν (x) − iYν (x)

8.1.5.1 First Order Bessel Function


Bessel Functions of the rst kind of order ν can be determined using the innite power series

KC
expansion of


X (−1)k (x/2)ν+2k
Jν (x) =
k=0
k!(ν + k)!

using the inbuilt library function in scipy.


C SR
The following code (prgs:bessel_functions.py) is used to plot the First Order Bessel function

Bessel Functions
AE
1 from scipy . special import a i r y , jn , eval_chebyt , e v a l _ l e g e n d r e
2 from matplotlib import pyplot as plt
3 import numpy as np
4 x = np . l i n s p a c e ( 0 , 1 4 , 1 0 0 0 )
CD

5 for i in range ( 2 ) :
6 p l t . p l o t ( x , j n ( i , x ) , l a b e l=i )
7 p l t . t i t l e (" Bessel f u n c t i o n s ")
8 plt . grid ()
9 plt . legend ()
10 p l t . show ( )
UG

The graphs of J0 and J1 ressemble those of cosine and sine with decreasing amplitude.

8.1.5.2 Zeros of Bessel Function


In the code below (prgs:bessel_functions_2.py), we have used the formula for the rst order
Bessel function, using the explicit expression. , and the results are presented in Fig.8.7.
8-26 Lecture 8: Python For Teaching Physics-I

Zeros of Bessel Functions

1 from matplotlib import pyplot as plt


2 import numpy as np
3
4 def jn (n , x ) :
5 jn = 0.0
6 for k in range ( 3 0 ) :
7 num = ( - 1 ) * * k * ( x / 2 . 0 ) * * ( n +(2 * k ) )

KC
8 den = ( np . math . f a c t o r i a l ( k ) ) * ( np . math . f a c t o r i a l ( n+k ) )
9 j n = j n + ( num/ den )
10 return jn
11
12 x = np . l i n s p a c e ( 0 , 1 4 , 1 0 0 0 )
13 for n in range ( 2 ) :
14
15
16
17
18
19
a = jn (n , x)
p l t . p l o t ( x , a , l a b e l =n )

p l t . t i t l e (" Bessel
plt . grid ()
plt . legend ()
C f u n c t i o n s ")
SR
20 p l t . show ( )
AE
CD

As seen from Fig.8.7, between two consecutive zeros of J0 there is exactly one zero of J1 .
The command from scipy.special import jn_zeros, print jn_zeros(0,10) , prints the zeros of
the correponding Bessel function. These can be veried with the tables and also from the
plotted results.
UG

8.1.5.3 Recursive Relations for Bessel Function


An important property of Bessel Function (of the rst order) is that

2n
Jn (x) = J(n−1) (x) + J(n+1) x
x
Lecture 8: Python For Teaching Physics-I 8-27

KC
C
Now we know that
SR
Figure 8.7: . Graph of J0 & J1 .

J0 (3.5) = − 0.3801
J1 (3.5) = 0.1374
AE
J2 (3.5) = 0.4586
Hence, from the above data

n = 1
x = 3.5
CD

Hence to compute J(n+1) (3.5)


2·1
J(n+1) (3.5) = Jn (x) − J(n−1) (3.5)
3.5
2·1
= J1 (3.5) − J0 (3.5)
3.5
UG

2·1
= (0.1374) − (−0.3801)
3.5
= 0.4589
which is in agreement with the tabulated value

The code below (prgs:bessel_recursion_1.py) demonstrates this Recursive Relation , and


prints out the actual value, computed value from the recursive relationship and the relative
dierence between the two.
8-28 Lecture 8: Python For Teaching Physics-I

Recursive Relation for Bessel Functions

1 import numpy as np
2 import matplotlib . pyplot as plt
3 from scipy import special
4
5 def recursion (n , x ) :
6 xp = x
7 j_npl = s p e c i a l . j v ( n +1 , xp )

KC
8 j _ n p l _ r e c = ( ( 2 . 0 * n / xp ) * s p e c i a l . j v ( n , xp ) ) - s p e c i a l . j v ( ( n - 1 ) , xp )
9 diff = abs ( j_npl - j_npl_rec )
10 rel_diff = ( diff / j_npl )
11 print j_npl , j_npl_rec , ( rel_diff )
12 print ( " The actual value is %1.18 f , computed value is %1.18 f " % ( j _ n p l , j_
13 print "\ n "
14
15
16
17
xl = 3.5
n=1
recursion (n , xl )
C
Thus the Recursive Relation helps us compute
SR
Jn (x) for any integer n if J(n−1) (x) &J(n+1) (x)
AE
are known.

8.1.6 Legendre's Polynomials


CD

The second order dierential equation

d2 y dy
(1 − x2 ) 2
− 2x + n(n + 1)y = 0 n > 0, |x| < 1
dx dx

is known as Legendre's equation . The general solution to these family of equations is given
UG

in terms of two Legendre functions as

y = APn (x) + BQn (x) |x| < 1


1 dn 2
Pn (x) = n n
(x − 1)n
2 n! dx
1 1+x
Qn (x) = Pn (x) ln
2 1−x
Where Pn (x) & Qn (x) are referred to as the Legendre function of the rst and second kind,
respectively, of order n.
Lecture 8: Python For Teaching Physics-I 8-29

The rst few Legendre Polynomials are

P0 (x) = 1
P1 (x) = x
1
P2 (x) = (3x2 − 1)
2

8.1.6.1 Recurrence Relationship for Legendre Polynomials

KC
The generation of Legendre Polynomials is aided by the recurrence relationship,

2n + 1 n
Pn+1 (x) = xPn (x) − Pn−1 (x)
n+1 n+1

The Python code (prgs_2:legendre_recur.py) given below attempts to calculate the Legendre

1
2
Polynomials using this recurrence relationship.
C
import
import
numpy as np
matplotlib . pyplot as
SR
Recursive Relation for Legendre Polynomials

plt
3
AE
4 def P( n , x):
5 i f ( n == 0 ) :
6 return 1 # P0 = 1
7 e l i f ( n == 1 ) :
CD

8 return x # P1 = x
9 else :
10 return (((2 * n) -1)*x * P( n - 1 , x ) - ( n - 1 ) * P( n - 2 , x ))/ f l o a t (n)
11
12
13 x= np . l i n s p a c e ( - 1 , 1 , 1 0 0 )
UG

14
15 for i in range ( 1 , 5 ) :
16 p l t . p l o t ( x , P( i , x ) , l a b e l ="P"+ s t r ( i ) )
17
18 p l t . l e g e n d ( l o c =" b e s t " )
19 p l t . t i t l e ( ' Legendre Polynomial ' )
20 plt . xlabel ( 'x ')
21 p l t . y l a b e l ( ' $P_n ( x ) $ ' )
22 p l t . show ( )
8-30 Lecture 8: Python For Teaching Physics-I

The results are plotted in Fig.8.8, which are in conformity with the plots in Fig.8.6 computed
using the built in library package scipy.special.legendre.

KC
C
Figure 8.8:
SR
. Legendre Polynomials from Recurrence Relationship.
AE

8.1.6.2 Orthogonality of Legendre Polynomial


CD

The Legendre polynomials Pm (x) & Pn (x) are said to be orthogonal in the interval −1 ≤
x ≤ 1, provided

Z 1
Pm (x) Pn (x)dx = 0 m 6= n
UG

−1
Z 1
2
Pm (x) Pn (x)dx = m=n
−1 2n + 1

The following Python code (prgs_2:legendre_ortho_1.py)attempts to prove the orthogonal-


ity condition for the Legendre Polynomial.
Lecture 8: Python For Teaching Physics-I 8-31

Recursive Relation for Legendre Polynomials

1 #Code f r o m Ms K B i s w a s
2 import numpy as np
3 from scipy . special import legendre as P
4 from scipy . integrate import quad
5 from numpy import poly1d
6
7 n=2
8 m=1

KC
9 y=np . p o l y m u l (P( n ) , P(m) )
10 I=quad ( y , - 1 . 0 , 1 . 0 ) [ 0 ]
11
12 print " the orthoganility condition for n=%i ,m=%i i s %f " %(n , m, I )

8.1.7
C
Spherical Harmonics
SR
AE
Spherical harmonics are an innite set of harmonic functions (functions which satises
2
Laplace's equation : ∇ f = 0), dened on the sphere.

Spherical harmonics arise from solving the angular portion of Laplace's equation in spherical
coordinates using separation of variables.
CD

 p
 (2) Klm cos(mφ) Plm (cosθ) ifm>0;
Yim (θ, φ) = K 0 P 0 (cosθ) f m = 0 ;
 pl l m (−m)
UG

(2) Kl sin(−mφ) Pl (cosθ) if m < 0

where Klm are the normalization constants and Plm are the associated Legendre polynomials,
such that

s
(2l + 1) (l − |m|)!
Klm =
4π (l + |m|)!
8-32 Lecture 8: Python For Teaching Physics-I

Now, for

r
1
l = 0, → Y00 (θ, φ) =

r
3
l = 1, → Y1−1 (θ, φ)
= sinφ sinθ

r
3
→ Y10 (θ, φ) = cosθ

KC

r
3
→ Y11 (θ, φ) = cosφ sinθ

r
15
l = 2, → Y2−2 (θ, φ) = sinφ cosφ sin2 θ
C →


Y2−1 (θ, φ) =

Y20 (θ, φ) =
r
r

r
5

15

16π
15
SR sinφ sinθ cosθ

(3 cos2 θ − 1)

→ Y2−1 (θ, φ) = cosφ sinθ cosθ


AE

r
15
→ Y22 (θ, φ) = (cos2 φ − sin2 φ) sin2 θ
16π
CD

r
1 35
l = 3 → Y3−3 (θ, φ) = sin3 θ sin3φ
8 π
r
−2 1 105
→ Y3 (θ, φ) = cosθ sin2 θ sin2φ
4 2π
r
−1 1 21
→ Y3 (θ, φ) = sinθ (5cos2 θ − 1) sinφ
UG

8 π
r
1 7
→ Y30 (θ, φ) = cosθ (5cos2 θ − 3)
4 π
r
1 1 21
→ Y3 (θ, φ) = sinθ (5cos2 θ − 1) cosφ
8 π
r
2 1 105
→ Y3 (θ, φ) = cosθ sin2 θ cos2φ
4 2π
r
1 35
→ Y33 (θ, φ) = sin3 θ cos3φ
8 π
Lecture 8: Python For Teaching Physics-I 8-33

Now the following Python script helps us plot these Spherical harmonics

Spherical Harmonics Y10


1 import numpy as np
2 from m p l _ t o o l k i t s . mplot3d import axes3d
3 import matplotlib . pyplot as plt
4
5 def sph2cart ( r , phi , tta ) :
6 ' ' ' r is from 0 to infinity ' ' '
2* p i

KC
7 ' ' ' phi is from 0 to ' ' '
8 ' ' ' tta is from 0 to pi ' ' '
9 x = r* np . s i n ( t t a ) * np . c o s ( p h i )
10 y = r* np . s i n ( t t a ) * np . s i n ( p h i )
11 z = r* np . c o s ( t t a )
12 return x, y, z
13
14
15
16
17
18
19
# phi running from
p h i = np . l i n s p a c e ( 0 ,
t t a = np . l i n s p a c e ( 0 ,
C
# meshgrid
phi ,
to generate
0 to
2*

t t a = np . m e s h g r i d ( p h i ,
pi

SR
and
np . p i ,
np . p i ,
points
100)

tta )
tta
100)
from 0 to pi
AE
20 # THIS I S THE FUNCTION
21 Y = 0 . 5 * np . s q r t ( 1 / np . p i )
22
23 # finally all things in cartesian co - o r d i n a t e system
24 # Note that "Y" is acting as "r"
CD

25 x, y, z = sph2cart ( np . a b s (Y) , phi , tta )


26
27 # plotting : -
28 fig = plt . figure ()
29 ax = f i g . add_subplot ( 111 , p r o j e c t i o n = '3d ' )
UG

30 ax . p l o t _ s u r f a c e ( x , y, z, linewidth = 0.5 , edgecolors = 'k ' )


31 ax . s e t _ a x i s _ o f f ( )
32 p l t . show ( )

The results are presented in the gure 8.9

Further an alternate Python script that helps us with plotting the Spherical harmonics is
8-34 Lecture 8: Python For Teaching Physics-I

KC
Figure 8.9: Three dimensional view of spherical harmonics.

0
Spherical Harmonics Y2,3
1
2
3
4
5
6
7
import
from
import
from

def
numpy

matplotlib

' ' '


C
sph2cart ( r ,
r is from
as

matplotlib . pyplot
np
m p l _ t o o l k i t s . mplot3d

import

phi ,
0 to
cm

tta ) :
infinity
as
import
plt
SR
axes3d

' ' '


2* p i
AE
8 ' ' ' phi is from 0 to ' ' '
9 ' ' ' tta is from 0 to pi ' ' '
10 r = 0.25 * np . s q r t ( 5 . 0 / np . p i ) * ( 3 * ( np . c o s ( t t a ) * * 2 ) - 1 )
11 x = r* np . s i n ( t t a ) * np . c o s ( p h i )
12 y = r* np . s i n ( t t a ) * np . s i n ( p h i )
CD

13 z = r* np . c o s ( t t a )
14 return x, y, z
15
16 # phi running from 0 to pi and tta from 0 to pi
17 p h i = np . l i n s p a c e ( 0 , 2* np . p i , 100)
UG

18 t t a = np . l i n s p a c e ( 0 , np . p i , 100)
19 # meshgrid to generate points
20 phi , t t a = np . m e s h g r i d ( p h i , tta )
21
22 # THIS I S THE FUNCTION
23 Y = 1
24 # finally all things in cartesian co - o r d i n a t e system
25 # Note that "Y" is acting as "r"
26 x, y, z = sph2cart ( np . a b s (Y) , phi , tta )
27
28 # plotting : -
29 fig = plt . figure ()
30 ax = f i g . add_subplot ( 111 , p r o j e c t i o n = '3d ' )
31 ax . p l o t _ s u r f a c e ( x , y, z, linewidth = 0.5 , edgecolors = 'k ' , cmap=cm . bwr )
32 ax . s e t _ a x i s _ o f f ( )
33 plt . t i t l e ( ' Spherical harmonics : l = 2 ; m = 0 ')
34 p l t . show ( )
Lecture 8: Python For Teaching Physics-I 8-35

The results are presented in the gure 8.10

KC
Figure 8.10:
C 0
panel : Y3 ) .

SR
Three dimensional view of spherical harmonics (Left panel : Y20 and Right

The package scipy.special , we have a function sph_harm(m,n,theta,phi) , which we shall


use when we use the Spherical Harmonics, to obtain the angular part of the wavefunction
for hydrogen atom.
AE

8.1.8 Sine & Cosine Series


CD

We know that the Sine and Cosine functions can be written as

x3 x5 x7
sin(x) = x − + − + ··· for all x
3! 5! 7!

X (−1)n 2n+1
= x
(2n + 1)!
UG

n=0
x2 x4 x6 x8
cos(x) = 1 − + − + − ···
2! 4! 6! 8!

X x2n
= (−1)n
n=0
(2n)!

The following code (prgs:series_sine_1.py) evaluates the Sine and (prgs:series_cosine_1.py)


Cosine functions respectively using the series. We can investigate the results, both qualita-
tively and quantitatively as a function as the number of terms we include in the summation.
8-36 Lecture 8: Python For Teaching Physics-I

Taylor series for sin(x)

1 import numpy as np
2 import matplotlib . pyplot as plt
3
4 xp = np . l i n s p a c e ( 0 , 2 * ( np . p i ) , 3 6 0 )
5 s = np . z e r o s ( 3 6 0 )
6 c = np . z e r o s ( 3 6 0 )
7

KC
8 def sin_approx ( x , n ) :
9 val = 0.0
10 series_sum = 0 . 0
11 for i in range (n ) :
12 series_sum = series_sum +(((( -1)** i ) * ( x ** (2 .0 * i + 1 ) ) ) / ( np . math . f a c t o r
13 return series_sum
14
15
16
17
18
19
for i in

s[ i ]
r a n g e ( l e n ( xp ) ) :
temp = ( s i n _ a p p r o x ( xp [ i ] , 8 ) )
C
= temp
SR
20 p l t . p l o t ( xp , s , "r - -")
AE
21 plt . grid ()
22 p l t . t i t l e (" Taylor series for f ( x)= S i n ( x ) " )
23 p l t . x l a b e l (" x ")
24 p l t . y l a b e l (" s i n ( x )")
CD

25 p l t . show ( )
UG
Lecture 8: Python For Teaching Physics-I 8-37

Taylor series for cos(x)

1 import numpy as np
2 import matplotlib . pyplot as plt
3
4 xp = np . l i n s p a c e ( 0 , 2 * ( np . p i ) , 3 6 0 )
5 c = np . z e r o s ( 3 6 0 )
6
7 def cos_approx ( x , n ) :
8 val = 0.0

KC
9 series_sum = 0 . 0
10 for i in range (n ) :
11 s e r i e s _ s u m = s e r i e s _ s u m + ( ( ( ( - 1 ) * * i ) * ( x * * ( 2 . 0 * i ) ) ) / ( np . math . f a c t o
12 return series_sum
13
14
15
16
17
18
19
20
for
C i in

c[ i ]
r a n g e ( l e n ( xp ) ) :
temp = ( c o s _ a p p r o x ( xp [ i ] , 1 0 ) )
= temp

p l t . p l o t ( xp , c ,
plt . grid ()
"g - - " )
SR
21 p l t . t i t l e (" Cosine Function f ( x)=Cos ( x ) " )
AE
22 p l t . x l a b e l (" x ")
23 p l t . y l a b e l (" cos ( x )")
24 p l t . show ( )
CD

8.1.9 Transcendental equation


A Transcendental equation is an equation which involves transcendental function , which
does not satisfy, a polynomial equation, i.e it cannot be expressed in terms of a nite sequence
of the algebraic operations such as addition, multiplication. Such equations do not have a
UG

closed-form solutions.

The solutions to transcendental equations are usually obtained graphically or analytically.


There is a library function in Python, which can be used to solve these equations. But for
the present, we shall use only the graphical and / or the analytical solution.

x2
If we wish to graphically, solve the equation sin(x) = 4
, then

1. Guess a range in which we expect the solution. Say 0 ≤ x ≤ 3.0


x2
2. Plot y1 = sin(x) & y2 = 4
, as a function of x.
8-38 Lecture 8: Python For Teaching Physics-I

3. The intersection of the two plots would give us the root of the equation.

The code below (prgs:graphical_soln_trans_1), attempts to graphically solve the above


equation. The results are presented in Fig. 8.11

Graphical Solution

1 import numpy as np
2 import matplotlib . pyplot as plt

KC
3
4 x = np . l i n s p a c e ( 0 , 3, 100)
5 y1 = np . s i n ( x )
6 y2 = x * x / 4 . 0
7
8 plt . plot (x , y1 , l a b e l =' s i n ( x ) ' )
9
10
11
12
13
p l t . p l o t ( x , y2 ,

plt . grid ()
plt . legend ()
C
p l t . show ( )
l a b e l ='x ^ 2 / 4 ' )
pl t . t i t l e ( ' Graphical Solution for

SR
s i n ( x)=x ^ 2 / 4 ' )
AE
CD
UG

x2
Figure 8.11: . Graph of sin(x) & 4
as a function of x.

As seen from Fig. 8.11, the two graphs, intersect around x ∼ 1.92, whereas the real root of
x2
the equation sin(x) = is 1.93.
4
Lecture 8: Python For Teaching Physics-I 8-39

x2
If we wish to solve analytically sin(x) = 4
for a non-zero root, then

x2
ˆ Let y1 = sin(x) & y2 = 4

ˆ Start with a value of x say x = 0.0 radian


ˆ Compute the value of y1 & y2
ˆ Then compute f (x) = y1 − y2
ˆ Increment the value of x, and repeat the above steps.

f (x) changes sign, ie., the value crosses

KC
ˆ The root of the equation is in the region, where
zero.

The code below (prgs:analytical_soln_trans_1.py), attempts at obtaining an analytical so-


lution the above equation. The results are illustrated in Fig. 8.12.

1
2
3
C
# Graphical
import
import
numpy
and
as
matplotlib . pyplot
Analytical
np
as
SRAnalytical Solution

Solution

plt
to s i n ( x)=x ^2/4

4
AE
5 x = np . l i n s p a c e ( 0 , 3, 20)
6 y1=np . z e r o s ( l e n ( x ) )
7 y2=np . z e r o s ( l e n ( x ) )
8 f=np . z e r o s ( l e n ( x ) )
CD

9
10 for i in range ( len ( x ) ) :
11 y1 [ i ] = np . s i n ( x [ i ] )
12 y2 [ i ] = x [ i ]*x [ i ]/4.0
13 f [ i ] = y1 [ i ] - y2 [ i ]
14 # print out values of x, and f (x)
UG

15 print (x [ i ] , f [ i ])
16
17 plt . plot (x , y1 , l a b e l =' s i n ( x ) ' )
18 p l t . p l o t ( x , y2 , l a b e l ='x ^ 2 / 4 ' )
19 plt . plot (x , f , l a b e l =' f ( x ) ' )
20 pl t . t i t l e ( ' Graphical & Analytical Solution for s i n ( x)=x ^ 2 / 4 ' )
21 plt . grid ()
22 plt . legend ()
23 p l t . show ( )
8-40 Lecture 8: Python For Teaching Physics-I

KC
C Figure 8.12: . Graph of

SR
sin(x) & x2
4
& f (x) as a function of x.
AE
As seen from the Fig. 8.12, the value of f (x), changes sign exactly at the same value of x,
x2
for which the graph of sin(x) & intersect.
4

Now, scipy , a package having inbuilt libraries for mathematical analysis, one of the li-

brary of relevance for nding roots of a given equation is, optimize . The code below
CD

(prgs:nd_roots_scipy_1.py) demonstrates the use of this function to obtain the solution


x2
of the above sin(x) = equation.
4
UG
Lecture 8: Python For Teaching Physics-I 8-41

Scipy : Find Roots

1 # Solution to Transcendental Equation using scipy


2 import numpy as np
3 import matplotlib . pyplot as plt
4 from scipy import optimize
5
6 def f (x ):
7 return x*x / 4 . 0 - np . s i n ( x )
8

KC
9 x = np . l i n s p a c e ( - 1 0 , 1 0 , 0 . 1 )
10 y = np . z e r o s ( ( l e n ( x ) ) )
11
12 for i in range ( len ( x ) ) :
13 result = f (x [ i ])
14 y[ i ] = result
15
16
17
r e s u l t =o p t i m i z e . r o o t ( f ,
print
C ( result . x)
2)

SR
Transcendental equations are of importance, in several problems in the domain of Quantum
Mechanics, as detailed in the subsequent section.
AE

8.1.10 Fourier Transform


Fourier transform, is a mathematical prescription to map a signal in time x(t) domain, into
CD

the frequency X(ω) domain.

We know that the Fourier Transform is a special case of the Fourier Series, when T → ∞,
is given by

+∞
X
x(t) = cn ejnω0 t where
UG

n=−∞
Z
1
cn = x(t)e−jnω0 t
T T
Z
1
T cn = x(t)e−jnω0 t hence
T T
Z +∞
X(ω) = x(t)e−jωt dt
−∞

It is numerically intensive to implement the Fourier Transform, and a solutuion to this is


8-42 Lecture 8: Python For Teaching Physics-I

provided by an algorithm known as Discrete Fourier Transform. The DFT of a signal of


x[n], where N is the size of the domain, can be expressed as

N −1
X j2πkn
X[k] = x[n]e− N where
n=0
N = number of samples

n = current sample

KC
x[n] = value of signal at the given instant n
k = current frequency

X[k] = Result of the DFT

Hence, to evaluate the DTF of a discrete signal


domain, which has to be mapped), we

ˆ
C
Obtain the product of x[n]
SR x[n] (where N

and the exponential term which is a function of


is the size of the original

n.

ˆ
AE
We then sum the results obtained.

We have to keep in mind that using the function dot product, from numpy package, we
CD

obtain

n
X
a·b = ai b i
n=1
UG

We shall use this feature, in our explicit calculation of the Fourier Transform.

The code below (prgs:t_demo.py) demonstrates, the use of both a user dened DFT func-
tion as well as the inbuilt t function.
Lecture 8: Python For Teaching Physics-I 8-43

Discrete Fourier Transform

1
2 import numpy as np
3 import matplotlib . pyplot as plt
4
5 d e f DFT( x ) :
6 N = x. size
7 n = np . a r a n g e (N)
8 k = n . r e s h a p e ( ( N, 1))

KC
9 e = np . e x p ( - 2 j * np . p i * k * n / N)
10 return np . d o t ( e , x)
11
12 t = np . l i n s p a c e ( 0 , 0.5 , 500)
13 s = np . s i n ( 4 0 * 2 * np . p i * t ) + 0 . 3 * np . s i n ( 1 2 0 * 2 * np . p i * t )
14
15
16
17
18
19
20
fft = np . f f t . f f t ( s )
T = t [1]
NN = s . s i z e
C
f u n = DFT( s )
- t [0] # sampling
SR interval

21
AE
22 f=np . l i n s p a c e ( 0 , 1 . 0 / ( 2 . 0 * T ) , NN/ 2 )
23
24 f f i g , a x s=p l t . s u b p l o t s ( 3 , g r i d s p e c _ k w ={ ' h s p a c e ' : 0.6 , ' wspace ' : 10.2})
25
*
CD

26 axs [ 0 ] . p l o t ( f , 2 . 0 /NN np . a b s ( f f t [ : NN/ / 2 ] ) , l a b e l = ' I n b u i l t fft ')


27 axs [ 0 ] . legend ( )
28 axs [ 0 ] . set_xlim ( 0 , 2 0 0 )
29 a x s [ 0 ] . s e t _ y l a b e l ( ' Arb . Units ' )
30 ax s [ 0 ] . s e t _ x l a b e l ( ' $ f r e q u e n c y $ ' , c o l o r =' b lu e ' )
31 axs [ 1 ] . p l o t ( f , 2 . 0 /NN * np . a b s ( f u n [ : NN/ / 2 ] ) , l a b e l = 'Our fft ')
UG

32 axs [ 1 ] . legend ( )
33 axs [ 1 ] . set_xlim ( 0 , 2 0 0 )
34 a x s [ 1 ] . s e t _ y l a b e l ( ' Arb . Units ' )
35 ax s [ 1 ] . s e t _ x l a b e l ( ' $ f r e q u e n c y $ ' , c o l o r =' b lu e ' )
36 a x s [ 2 ] . p l o t ( t , s , l a b e l =' I n p u t Waveform ' )
37 axs [ 2 ] . legend ( )
38 a x s [ 2 ] . s e t _ x l a b e l ( ' $time$ ' , c o l o r =' red ' )
39 a x s [ 2 ] . s e t _ y l a b e l ( ' Amplitude ' )
40 p l t . show ( )
8-44 Lecture 8: Python For Teaching Physics-I

The results of the code, are presented in Fig. 8.13.

KC
C SR
Figure 8.13: . Fourier Transform of a Sinusoidal Waveform.
AE

We have constructed the input wave as a sinusoidal wave with f0 = 40 Hz and f3 = 120
Hz, with the amplitude of the thrird harmonic, being one-third, that of the fundamental
CD

fequency.

As seen from the Fourier Transform, we do see that the output, has indeed two frequencies ,
with their respective amplitudes, in the expected ratio.

8.1.11 Dirac Delta Function


UG

A function routinely used in the analysis of electrical signals, is known as Heaviside step
function, which is mathematically represented as
(
1 for x>0
H(x) =
0 for x<0

This is a discontinuous function , with a discontinuity at x = 0. It was around 1930 that


Paul Dirac investigated the following function, termed as delta function, to describe an
Lecture 8: Python For Teaching Physics-I 8-45

extremely localized charge density,

(
+∞ for x = 0
δ(x) =
0 for x 6= 0

With an additional constraint that

Z +∞
δ(x)dx = 1

KC
−∞

Unfortunately, both these denitions are mutually not compatible, ie, there does not exist
a single function δ(x) which satises both the above equations. This was circumvented by
Dirac, by tweaking the interpretation of the integral as

where
C
δ (x),
Z +∞

−∞

is a generic function of both


SR
δ(x)dx = lim δ (x)dx

x & ,
(
→0+

such that

+∞ for x = 0
AE
lim δ (x)dx =
→0+ 0 for x 6= 0
Z +∞
δ (x)dx = 1
−∞
CD

In 1950 Laurent Schwartz was to show that δ -functions are (not functions , either proper
or improper, but) are mathematical objects of a fundamentally new type distributions ,
which kind of are swept in a shade of an integral.

The Gaussian function, for instance is an example of δ (x),


UG

1 2 2
δ (x) = √ e−x /
 π

whose integral is equal to 1 for any value of . The code (prgs_2:gaussian_dirac.py) below
attempts to illustrate the above
8-46 Lecture 8: Python For Teaching Physics-I

Dirac Delta Function

1 #GAUSSIAN FUNCTION a s DIRAC' S DELTA FUNCTION


2 #Code f r o m Ms K B i s w a s
3 import numpy as np
4 import scipy
5 from scipy . integrate import quad
6 import matplotlib . pyplot as plt
7
8 #e x p r e s s i o n of delta function using Gaussian function

KC
9 F=lambda x: (1.0/( s * ( 2 * np . p i ) * * 0 . 5 ) ) * ( np . e x p ( ( - ( x -m) * * 2 ) / ( 2 * ( s **2))))
10 m= 1 0 . 0 #mean
11 s =0.01 #s t a n d a r d deviation
12 n=10
13 p=m + n * s #u p p e r limit
14 q=m - n* s #l o w e r limit
15
16
17
I=quad ( F , q , p )

print " the


C value of the integration
SR using quad i s =" , I [ 0 ]
AE
Hence, naively, we can vizualize the Dirac Delta Function, as a rectangle whose area equals
1, with one side extending all the way up to +∞.
CD

8.2 Quantum Mechanics

8.2.1 Eigen-analysis
UG

8.2.1.1 Eigen Value


Given and n×n matrix, det(A − λI) = 0 denes a polynomial of degrees n in the unknown
λ.
This is referred to as characteristic equation

It yields n eigenvalues , which can be solved to obtain the eigenvectors


Lecture 8: Python For Teaching Physics-I 8-47

 
a a
If A is 2×2 matrix, such that A = 11 12 , then the Characteristic equation is
a21 a22
   
a11 a12 λ 0
A − λI = −
a21 a22 0 λ
 
a11 λ a12
=
a21 a22 − λ

a11 λ a12
det(A − λI) =

a21 a22 − λ

KC
= (a11 − λ)(a22 − λ) − a12 a21
= λ2 − (a11 + a22 )λ + a11 a22 − a12 a21
= λ2 − T rλ + Det
= 0
where

C Tr =
=
Det =
=
SR
T race(A)
a11 + a22
det(A)
a11 a22 − a12 a21

Now, trace is dened as the sum of all the diagonal entries.


AE
 
0 1
Consider a 2×2 matrix A = .
−2 −3
Then the characteristic equation is
CD


  
0 1 λ 0
A − λI = −
−2 −3 0 λ
 
−λ 1
=
−2 −3 − λ
UG

 
−λ 1
det(A − λI) =
−2 −3 − λ
= − λ(−3 − λ) − 1(−2)
= λ2 + 3λ + 2

The solution of the above equation yields λ = −2 & λ = −1, which are the eigen-values

In scipy , we have a library function linalg which has modules to compute the bf eigenvalues
of a square matrix, which is eig. The use of this function is illustrated in the code below
8-48 Lecture 8: Python For Teaching Physics-I

Compute Eigenvalues

1 import numpy as np
2 import matplotlib . pyplot as plt
3 import scipy . lin al g as la
4 A=np . a r r a y ( [ [ 0 , 1 ] , [ - 2 , - 3 ] ] )
5 w , v = l a . e i g (A)
6 print w

KC
The command w,v = la.eig(A), helps us obtain the eigenvalues - w and the eigenvectors - v ,
for the given square matrix A.

8.2.1.2 Eigen Vectors

then for each eigenvalue,


C λi (i = 1, ..., n)
SR
To compute the eigen vextors of a square matrix, rst nd the eigenvalues of the matrix,
solve the linear equation

(A − λi I)~v = ~0 for v~i 6= 0

 
AE
−2 1
Now let us consider a 2×2 square matrix, A = .
12 −3
We rst compute the eigenvalues, as λ=1 & −6
Now the eigenvectors for λ=1 can be determined by substituting λ=1 in the equation
CD

(A − λI)X = 0

   
−2 1 1 0
−1 X = 0
12 −3 0 1
UG

   
−2 1 −1 0
+ X = 0
12 −3 0 −1
 
−3 1
X = 0
12 −4
  
−3 1 x1
= 0
12 −4 x2

The above system of equations can be solved using the conventional Gauss Elimination ,
whose details are beyond the present scope.
Lecture 8: Python For Teaching Physics-I 8-49

If we were to solve these set of equation, the eigenvector X corresponding to eigenvalue


λ = 1, maybe viewed as
1
X = t 3 , tR
1

Similarly, the eigenvector X corresponding to eigenvalue λ = −6, maybe viewed as


 −1 
X = t 3 , tR
1

KC
An important property of the eigenvectors, is that the ratio of eigenvectors, is always con-
stant, we may obtain dierent sets of absolute numerical values, with the constraint that the
ratios would be constant

The following code computes both the Eigenvalues and vectors for a given square matrix.

1
2
3
C
import
import
import
numpy as np
matplotlib . pyplot
scipy . lin al g as la
as
SR
Compute Eigenvalues and Eigenvectors

plt
AE
4
5 A=np . a r r a y ( [ [ - 2 , 1 ] , [ 1 2 , - 3 ] ] )
6 w , v = l a . e i g (A)
7 print w, v
CD

8.2.2 Transcendental Equations for Finite Square Well Potential


The mathematics of quantum mechanics is usually introduced through physical systems,
described by one dimensional potential wells. Of these the nite quantum well provides us
UG

with the basis for understanding the underlying methodology.

The most standard problem is to solve for the energies of a particle of mass m bound within
the 1−D square well of radius a, such that potential is described as :
(
0 (−a ≤ x ≤ a)
V (x) =
V0 otherwise

The mathematical details of the methodology can be found in any standard textbook on the
subject, and is beyond the scope of the present eort.
8-50 Lecture 8: Python For Teaching Physics-I

We know that the bound-states are alternately even and odd functions, such that

(
kn tan(kn a) (n = 1, 3, 5, ....)
κn =
−kn cot(kn a) (n = 2, 4, 6, ...)
where
p
(2m(V0 − E)
κn =
~

KC
The above equation can be solved graphically, if we consider the following dimensionless
quantities

C =
ap
~
2mEn
SR
ζ : is a dimensionless measure of energy
= kn a

ζ0 : is a dimensionless measure of the size


=
ap
~
2mV0
(depth) of the well
AE

Using the above notation, we have


CD

s (
ζ0 2 tan(kn a) (n = 1, 3, 5, ....)
−1=
ζ − cot(kn a) (n = 2, 4, 6, ...)
UG

The above equation represents, a transcendental equations, which can be solved graphically.
If we were to plot both the LHS and RHS of the equation, for ζ0 = 15, on the same graph,
then the the points of intersection represents solutions.

The below code helps us obtain a graphical solution to the above transcendental equation,
and the plost are presented in Fig. 8.14.
Lecture 8: Python For Teaching Physics-I 8-51

Finite Well Graphical Solution

1 # From Griffiths
2 import numpy as np
3 import matplotlib . pyplot as plt
4 import math as mt
5
6 E=np . l i n s p a c e ( 0 , 6 * np . p i , 1 0 0 0 )
7
8 y1= np . t a n (E)

KC
9 y3 = - 1 . 0 / np . t a n (E)
10 y2 = np . s q r t ( ( 1 5 / E ) * * 2 - 1 . 0 )
11 p l t . ylim ( 0 , 1 5 )
12 p l t . p l o t ( E , y1 , l a b e l = ' t a n ( z ) ' )
13 p l t . p l o t ( E , y2 , l a b e l =' s q r t ( z0 / z ) ^ 2 - 1 ' )
14 p l t . p l o t ( E , y3 , l a b e l =' c o t ( z ) ' )
15
16
17
18
plt . xlabel ( 'z ')
plt . grid ()
plt . legend ()
p l t . show ( )
C SR
AE
CD
UG

Figure 8.14: . Graphical solution for nite square well for ζ0 = 15.

From the gure Fig. 8.14, based on the visual inspection, for points of intersection of the
graphs, the roots of the transcendental equation are summarized in the table below.
8-52 Lecture 8: Python For Teaching Physics-I

Table 8.3: Comparison of the present graphical results with the reported results of O. F. de
Alcantara Bonma and D J Griths, Ref : http://pilotscholars.up.edu/phy_facpubs/8

En
n ζn ζn V0
From graph From Griths
1 1.4 1.472 0.0087
2 2.8 2.9 0.034
3 4.4 4.4 0.086
4 5.9 5.9 0.154

KC
5 7.2 7.3 0.23
6 8.8 8.8 0.34

SR
Now, if we were make the well shallower, (decrease the value of ζ0 ), there are fewer and fewer
π
solutions. For example is we make ζ0 ≤ , only one solution (n = 1), survives.
2

Another feature, which is clearly elucidated by the graph is that as the well gets broad-
π
er/deeper more and more solutions occur and the intersections approaches ζn = n . For
C π
2
example, for n = 6, we have ζ6 = 8.8graph = 6[ ] = 9.4
2

In addition to graphical solution, transcendental equations also have an numerical solution,


which are obtained using the in-built routines or libraries in scipy . It is generally perceived
AE
that Brent's method (the details of which are beyond the present scope) to nd a zero of the
function f (x) on the sign changing interval [a, b] is the best rootnding routine available in
scipy. The arguments to this routine are f, a, b , where the function f , must be continuous
and f (a) & f (b), must have opposite signs.
CD

Now, we have another routine in numpy.sign , which returns the element-wise indication of
the sign of the number, passed as it's argument.

Suppose, the given array A = [−5.5, −4.5, 5.5, 6.5], then np.sign(A), where we have aliased
(imported) numpy as np , would give the result as [-1.,-1.,1.,1.].

sign command, is zero, it


UG

Hence, if the sum of two consecutive elements in the result of the


indicates that there has been a change of sign. This is used to identify, where the function
has changed signed, and then we can determine it's roots.

The code below achieves the numerical solution to the nite square well potential problem
which has whose solution has been obtained graphically earlier.
Lecture 8: Python For Teaching Physics-I 8-53

Finite Well Numerical Solution

1 # From Griffiths
2 import numpy as np
3 import matplotlib . pyplot as plt
4 from scipy . integrate import odeint
5 from scipy . optimize import brentq
6 from scipy . optimize import root
7
8 z0 =15.0

KC
9
10 # functions for even n
11 def fo ( z ) :
12 global z0
13 if ( ( z== 0 ) or ( ( z %(np . p i / 2 . 0 ) ) = = 0)):
14 return 0
15
16
17
18
19
20
def
C else

#f u n c t i o n s
fe (z ):
global
:
return

for

z0
odd n
SR
- 1 . 0 / np . t a n ( z ) - np . s q r t ( ( z 0 / z ) * * 2 - 1 )

21 if ( ( z== 0 ) or ( ( z%np . p i )== 0 ) ) : # to avoid divide by zero at tan ( 9 0


AE
22 return 0
23 else :
24 return np . t a n ( z ) - np . s q r t ( ( z 0 / z ) * * 2 - 1 )
25
z=np . l i n s p a c e ( 0 . 0 0 0 1 , 6 * np . p i , 1 0 0 0 )
CD

26
27 f_yo = np . z e r o s ( l e n ( z ) )
28 f _ y e = np . z e r o s ( l e n ( z ) )
29
30 for i in range ( len ( z ) ) :
31 resulto = fo ( z [ i ] )
UG

32 f_yo [ i ] = resulto
33 resulte = fe (z [ i ])
34 f_ye [ i ] = resulte
35
36 # obtaining the sign of the function
37 s e=np . s i g n ( f _ y e )
38 for i in range ( len ( se ) - 1 ) :
39 if s e [ i ]+ s e [ i +1] == 0 :
40 # if the sum of two consecutive elemnst is zero : change of sign for
41 zero = brentq ( fe , z[ i ] , z [ i +1])
42 print zero
43
44 s=np . s i g n ( f_yo )
45 for i in range ( len ( s ) - 1 ) :
46 if s [ i ]+ s [ i +1] == 0 :
47 zero = brentq ( fo , z[ i ] , z [ i +1])
48 print zero
8-54 Lecture 8: Python For Teaching Physics-I

Table 8.4: Numerical solutions to nite square well potential

1.472473107 2.94404080448 Accept


1.57079632679 3.14159265359 Ignore
4.41372036547 5.88035499793 Accept
4.71238898038 6.28318530718 Ignore
7.34246782552 8.79800556095 Accept
7.85398163398 9.42477796077 Ignore
10.2438199622 11.6744248115 Accept

KC
Caution While deciphering the output (Table 8.1), please ignore the alternate values, since
π
they correspond to the z = n · . The results of the numerical solutions for the odd tan(ζ),
2
are

p
2 (V0 − E)E
r
SR
As seen from the above exercise, we have an excellent agreement with both the graphical as
well as the numerical solutions for the nite quantum well.

We know that these transcendental equations, can also be written as


C
2mEL2

= tan
AE
(2E − V0 ) ~2

We know that if we were to use atomic units, them me , ~ & q would be 1. However, if we
CD

wish to consider an electron in a nite well 0.5nm wide and 25 eV deep, then we shall use
the following units,

me c2 = 5 × 105 eV
~c = 197 eV − nm
UG

V0 = 25.0 eV
E : 0 ≤ E ≤ 25eV

The following code attempts to graphically solve the above problem, and results are presented
in Table.8.3
Lecture 8: Python For Teaching Physics-I 8-55

Electron In a Finite Well Graphical Solution

1 #h t t p s : / / p e o p l e . r i t . edu / v w l s p s / 3 1 4_w07/ F i n i t e S q u a r e W e l l . p d f
2 import numpy as np
3 import matplotlib . pyplot as plt
4
5 E=np . l i n s p a c e ( 0 . 1 , 3 0 , 1 0 0 0 )
6 U = 25.0
7 m = 5 . 0 * 1 0 * * 5 # m_c^2
8 L = 0 . 5 # nm

KC
9 hbar = 197 #
10
11 y1 = ( 2 . 0 * np . s q r t ( ( U- E) * E ) ) / ( ( 2 . 0 * E ) -U)
12 temp_y2 = np . s q r t ( ( 2 . 0 * (m) * E* L * L ) / ( h b a r * h b a r ) )
13 y2 = np . t a n ( temp_y2 )
14
15
16
17
18
19
20
p l t . p l o t ( E , y1 ,
p l t . p l o t ( E , y2 ,
plt . grid ()
plt . legend ()
C
plt . t i t l e ( ' Electron
p l t . ylim ( - 5 5 , 5 5 )
l a b e l = 'LHS ' )
l a b e l = 'RHS ' )

in a
SR
finite well ' )

21 p l t . show ( )
AE

Table 8.5: Comparison of the graphical solution of electron in a nite square well, with the
CD

reported results https://people.rit.edu/vwlsps/314_w07/FiniteSquareWell.pdf

Present Reported
1.2 1.123
4.4 4.461
UG

10.01 9.905
17.37 17.162
24.6 24.782

It is worth mentioning that the present results, which have been obtained following a visual
inspection of the points of intersection, are in agreement with the reported values.

As seen from the plot, no solution of the bound states, exists for energy greater than the
potential depth.
8-56 Lecture 8: Python For Teaching Physics-I

8.2.3 Scattering from Step Potential


We know that a particle is either considered to be free or bound or scattered. Hence, the
particle could be a free state (no potential acting on it), or in a bound state, ( a potential
that holds the particle for a non zero period of time), or in a scattered state (can be described
as an interaction of a free particle with a potential that results in a free particle).

The details regarding the solution of the Schrödinger equation for a step potential,

KC
0 if x < 0
V (x) =
V0 if x > t

We know that the wavefunction can be factorized as

C Ψ(x, t) = e− /~ Ψ(x)

k< =
r
2mE
r ~
2
iEt

SR
Ψ1 (x) = Aeik< x + Be−ik>x , x < 0,
Ψ2 (x) = Ceik> x x > 0, region 2
region1

2m(E − Vo )
AE
k> =
~2

Where, the subscripts indicate the regions as dened in the potential.


CD

Now, we know that the transmittivity T , is given by

4k< k>
T =
(k< + k> )2
UG

And the reectivity R, is given by

R=T −1

The code below, helps us calculate the T & R, for an electron incident on a step-potental
U0 = 15.0, and the results are plotted in Fig. 8.15.
Lecture 8: Python For Teaching Physics-I 8-57

Electron Scattering from Step Potential

1 #S c a t t e r i n g from step potential


2 import numpy as np
3 import matplotlib . pyplot as plt
4 import cmath
5 import math
6
7 E=np . l i n s p a c e ( 0 . 0 0 0 0 1 , 5 0 , 1 0 0 0 )
8 Ev=np . v e c t o r i z e (E)

KC
9 k l = np . z e r o s ( l e n (E ) )
10 kg = np . z e r o s ( l e n (E ) )
11 T = np . z e r o s ( l e n (E ) )
12 R = np . z e r o s ( l e n (E ) )
13
14 U = 15.0
15
16
17
18
19
20
m = 5 . 0 * 1 0 * * 5 # mec^2
L = 0 . 5 # nm
hbar = 197 #

for
C
i in r a n g e ( l e n (E ) ) :
SR
z = c o m p l e x ( cmath . s q r t (E [ i ] - U) )
21 x = z . real
AE
22 kl [ i ] = np . s q r t ( ( 2 . 0 * m*E [ i ] ) / ( h b a r * h b a r ) )
23 kg [ i ] = np . s q r t ( ( 2 . 0 * m) / ( h b a r * h b a r ) ) * x
24 T[ i ] = ( 4 * k l [ i ] * kg [ i ] ) / ( ( k l [ i ]+ kg [ i ] ) * * 2 )
25 R[ i ] = 1.0 -T [ i ]
CD

26
27 print ( sum (R) , sum (T ) )
28 p l t . p l o t (E , T, l a b e l = 'T ' )
29 p l t . p l o t (E , R, l a b e l = 'R ' )
30 plt . grid ()
31 plt . legend ()
UG

32 plt . t i t l e ( ' Scattering from Step Potential ' )


33 p l t . show ( )

The code in Lines 20 & 21, ensures that we are able to compute the square root of a negative
number, when E < U, and extract the real part, which corresponds to zero.

We also obtain the quantitative estimate for R, and it can be shown that, the fraction of the
beam that is reected depends on the relative height of the step.
8-58 Lecture 8: Python For Teaching Physics-I

KC
8.2.4
Figure 8.15:

Scattering from Potential Well


C SR
Scattering from a Step Potential.

In the earlier section, we have demonstrated the scattering from a step potential . Now, we
shall, consider, the problem wherein, we now consider a beam of particles incident upon a
AE
square potential barrier of height V0 , and width a,


 0 if x ≤ 0
V (x) = V0 if 0 ≤ x ≤ a
CD


0 if x ≥ a

We know that, the solutions to the Schrödinger equation, would entail, the following factors,
r
2mE
k1 = 2
r ~
UG

2m(E − Vo )
k2 =
~2
such that the Transmittivity T , is given by

1
T =  2
1 k1 k2
1+ 4 k2
− k1
sin2 (k2 a)

with Reectivity as
R=1−T
Lecture 8: Python For Teaching Physics-I 8-59

The code below, allows us to obtain the transmissivity, and the results, presented in Fig. 8.16.

Electron Scattering from a Finite Barrier

1 #E l e c t r o n In a Finite Potential Barrier


2 import numpy as np
3 import matplotlib . pyplot as plt
4 import cmath
5

KC
6 E=np . l i n s p a c e ( 0 . 0 0 0 1 , 3 0 , 1 0 0 0 )
7 #U = f l o a t (" i n f ")
8 U = 10.0
9 m = 5 . 0 * 1 0 * * 5 # mec^2
10 L = 0 . 5 # nm
11
12
13
14
15
16
17
hbar = 197 #

E=np . l i n s p a c e ( 0 . 0 0 0 0 1 , 5 0 , 1 0 0 0 )
Ev=np . v e c t o r i z e (E)
C
k1 = np . z e r o s ( l e n (E ) )
k2 = np . z e r o s ( l e n (E ) )
T = np . z e r o s ( l e n (E ) )
SR
18 R = np . z e r o s ( l e n (E ) )
AE
19
20
21 for i in r a n g e ( l e n (E ) ) :
22 z = c o m p l e x ( cmath . s q r t (E [ i ] - U) )
CD

23 x = z . real
24 k1 [ i ] = np . s q r t ( ( 2 . 0 * m*E [ i ] ) / ( h b a r * h b a r ) )
25 k2 [ i ] = np . s q r t ( ( 2 . 0 * m) / ( h b a r * h b a r ) ) * x
26 T[ i ] = 1.0/(1.0 + ( 0 . 2 5 * ( ( ( k1 [ i ] / k2 [ i ] ) - ( k2 [ i ] / k1 [ i ] ) ) * * 2 ) ) * ( np . s i n ( k
27 R[ i ] = 1.0 -T [ i ]
28
UG

29 p l t . p l o t (E , T, l a b e l = 'T ' )
30 #p l t . p l o t ( E , R , l a b e l = 'R ' )
31 plt . grid ()
32 plt . legend ()
33 plt . t i t l e ( ' Electron in a finite potential barrier ')
34 p l t . xlim ( 0 , 3 5 )
35 p l t . x l a b e l ( 'E' )
36 p l t . y l a b e l ( 'T' )
37 p l t . show ( )
8-60 Lecture 8: Python For Teaching Physics-I

KC
Figure 8.16:
C SR
Reection and Transmission coecients for a nite potential barrier.

As seen from Fig. 8.16, in region just beyond E/V0 >1 particle has enough energy to across
the barrier, and proceed forward, but the wave function has a signicant probability to be
reected back, which cannot be envisaged classically.

The oscillatory behavior of T is essentially due to the sin2 (k2 a) term.


AE

8.2.5 Central Potential : Hydrogen Atom.


CD

If the given potential is central , ie., it depends only on the distance from the centre, and
exhibits a spherical symmetry, then even though the V, depends on r, the wavefunctions
would however, depend on both θ & φ, such that (from seperation of variables)
UG

Ψ(r, θ, φ) = R(r)Ylm (θ, φ)

R(r), is the radial part is inuenced by the actual shape of the potential V (r), whereas the
angular part of the wavefunction represented by the Spherical Harmonics, Y (θ, φ), is same
for all spherically symmetric potentials.

The Coulomb Potential is an example of a spherically symmetric potential. For a hydrogen


atom, we have a relatively heavy and motionless proton, which can be considered to be
placed at the origin, around which the much lighter electron revolves, such the Coulomb
potential, is given by
Lecture 8: Python For Teaching Physics-I 8-61

1 −e2
V (r) =
4π0 r

Given this potential energy, we arrive at the eective potential, as

~2 l(l + 1) 1 e2
Vef f (r) = −
2me r2 4π0 r

KC
Now the radial Schrödinger equation can be written as

~2 d2 u
 
− + Vef f (r) u(r) = Eu(r)
2me dr2

C SR
We now, solve the radial part to obtain the allowed energies

The discussion, on the methodology to obtain the solutions is beyond the scope of this
manuscript. However, one point to be kept is mind, is that one encounters usually two set
of units being used in these problems.
AE
1. Atomic units

2. Conventional units

We also refer to a quantity a0 , known as the Bohr Radius , such that


CD

~2/me
a0 = e2/4π

= 0.529 × 10−10 m

atomic unit system


UG

The sets all four constants me , ~, e & 1/4π equal to 1.

The rst few radial wave functions for hydrogen atom Rn,l (r) [Refer Introduction to Quan-
tum Mechanics by D J Griths]

−3/2
R1,0 = 2a0 e− /a0
r

 
1 −3/2 r 1 r (−r/2a0 )
R2,0 = √ a0 1− e
2 a0 2 a0
1 −3/2 r (−r/2a0 )
R2,1 = √ a0 e
24 a0
8-62 Lecture 8: Python For Teaching Physics-I

After having obtained the radial wavefunction, say Ψ1,s (r), following Born's interpretation
of the wavefunction, the probability per unit volume of nding the electron at the point
(r, θ, φ), would be obtained from the square of the normalized wavefunction,

ρ1,0 (r) = [Ψ1,0 (r)]2

KC
However, a more signicant measure, is the radial distribution function, dened as

C SR
D1,0 (r) = 4πr2 [Ψ1,0 (r)]2

which represents the probability density within the entire shell of radius r, such that
AE

Z ∞
D1,0 = 1
CD

The code below, obtains the radial wavefunction for the n = 1, l = 0 (1s) state of the
UG

hydrogen atom, from the expressions as detailed bi Griths, and computes both ρ(r) & D(r),
for the state. The results are presented in Fig.8.17.
Lecture 8: Python For Teaching Physics-I 8-63

Hydrogen Wavefunctions for 1s

1 # Griffiths pg 141 ; n =1 , l =0
2 import matplotlib . pyplot as plt
3 import numpy as np
4
5 a = 5.29*10** -11
6 r = np . l i n s p a c e ( 0 , 52.9*10** -11 , 1000)
7
8 P s i = np . z e r o s ( l e n ( r ) )

KC
9 r h o = np . z e r o s ( l e n ( r ) )
10 d e n s = np . z e r o s ( l e n ( r ) )
11
12 r = r /a
13
14 P s i = 2 * ( a * * ( - 3 . 0 / 2 . 0 ) ) * np . e x p ( - r )
15
16
17
18
19
20
rho = Psi * Psi
d e n s = 4 * np . p i * r * r * P s i * P s i

fig ,
C axs = p l t . s u b p l o t s ( 3 ,
f i g . s u p t i t l e ( ' Hydrogen
axs [ 0 ] . p l o t ( r , Psi ,
SR
g r i d s p e c _ k w ={ ' h s p a c e ' :
Wavefunctions
l a b e l =' Psi ' )
for n =1 , l =0 ')
0.6 , ' w sp a c e ' : 0.9})

21 axs [ 0 ] . g r i d ( )
AE
22 axs [ 0 ] . legend ( )
23 axs [ 1 ] . p l o t ( r , rho , l a b e l =' rho ' )
24 axs [ 1 ] . g r i d ( )
25 axs [ 1 ] . legend ( )
CD

26 axs [ 2 ] . p l o t ( r , dens , l a b e l =' D ensit y ' )


27 axs [ 2 ] . g r i d ( )
28 axs [ 2 ] . legend ( )
29 a x s [ 2 ] . s e t _ x l a b e l ( ' r / ao ' )
30 p l t . show ( )
UG

The x − axis is labelled in terms of r/a0 bohr.

As seen from the gure, the radial distribution function for the (1s) state has maximum at
r = a0 .
In the above code, if we were to replace the Line 14 , with
Psi = (1.0/(np.sqrt(2)))*(a**(-3.0/2.0))*(1.0-(1.0/2.0)*(r))*np.exp(-r/2.0) we shall obtain
the information for Ψ2s (r), ρ2s (r), D2s (r), for hydrogen atom.
8-64 Lecture 8: Python For Teaching Physics-I

KC
8.2.6
Figure 8.17: Graphs for

SR
Ψ1s (r), ρ1s (r), D1s (r)

Symmetric Potential: Harmonic Oscillator


C
Let us consider the symmetric potential
for Hydrogen atom.
AE
1
V (x) = k s x2
2
1
= mωc2 x2
2
r
ks
CD

ωc =
m

For this potential, we now have to solve the Schrödinger equation,

~ 2 dΨ 1
− + mωc2 x2 Ψ = EΨ
UG

2m dx 2 2

We then introduce the dimensionless variable


r
mωc
ξ = x
~

and the Schrödinger equation, can now be written as

d2 Ψ
2
= (ξ 2 − K)Ψ

Lecture 8: Python For Teaching Physics-I 8-65

Where, K is the energy in units of 1/2~ωc , such that

2E
K ≡
~ωc

The solution of the above equation results, in the wavefunction, being described as
 1/4
mωc 1 2
Ψn (x) = √ Hn (ξ)e−ξ /2
π~ n
2 n!
Where Hn (ξ) are the Hermite Polynomials

KC
The code, below, calculates the wavefunction for a Harmonic Oscillator, using the analytical
expression and Hermite Polynomials. We have used the inbuilt, hermite module in the
numpy package. The parameter n sets the order for the Hermite Polynomial. Having
obtained the wavefunction we also compute the Probability density, for the same. The
results are presented in Fig. 8.18.

1
2
3
4
5
6
7
8
9
10
C from __future__ import d i v i s i o n
from numpy . p o l y n o m i a l . h e r m i t e import *
from s c i p y import i n t e g r a t e
from s c i p y import o p t i m i z e
import numpy a s np
import pylab
import math
# us e n a t u r a l u n i t s where c = h_bar = 1
m = 1
w = 1
SR
Harmonic Oscillator Wavefunctions

11 h_bar = 1
AE
12 n = 1
13
14 fun = lambda xs : ( 1 / ( math . pow ( 2 , n ) * math . f a c t o r i a l ( n ) ) * * 0 . 5 * (m*w/ ( np . p i *h_bar ) ) * * 0 . 2 5 * ( np . exp ( -m*w* xs * * 2 / ( 2 *
15
16 fun_not = lambda xs : ( ( np . exp ( -m*w* xs * * 2 / ( 2 * h_bar ) ) * hermval ( (m*w/h_bar ) * * 0 . 5 * xs , herm_coeff ) ) ) * * 2
17
18 p i = np . p i
19 x_min = -20
20 x_max = -x_min
CD

21 xs = np . l i n s p a c e ( x_min , x_max, 1 0 0 0 0 )
22 zeros = [ ]
23 p s i = np . z e r o s ( l e n ( xs ) )
24 p_inf=f l o a t ( " i n f " )
25 n_inf=f l o a t ( " - i n f " )
26 # c o e f f i c i e n t s f o r Hermite s e r i e s , a l l 0 s e x c e p t t h e n - th term
27 herm_coeff = [ ]
28 f o r i in range (n ) :
29 herm_coeff . append ( 0 )
30 herm_coeff . append ( 1 )
31
32 f o r i i n r a n g e ( l e n ( xs ) ) :
UG

33 temp1 = ( np . exp ( -m*w* xs [ i ] * * 2 / ( 2 * h_bar ) ) * hermval ( (m*w/h_bar ) * * 0 . 5 * xs [ i ] , herm_coeff ) )


34 temp2 = 1 / ( math . pow ( 2 , n ) * math . f a c t o r i a l ( n ) ) * * 0 . 5 * (m*w/ ( np . p i *h_bar ) ) * * 0 . 2 5
35 temp_f = temp1 * temp2
36 p s i [ i ] = temp_f
37
38 s = np . s i g n ( p s i )
39 f o r i in range ( len ( p s i ) - 1 ) :
40 i f s [ i ]+ s [ i +1] == 0 :
41 z e r o = o p t i m i z e . b r e n t q ( fun , p s i [ i ] , p s i [ i +1])
42
43 r e s u l t , e r r = i n t e g r a t e . quad ( fun , n_inf , p_inf )
44 print result
45 pylab . p l o t ( xs , p s i )
46 pylab . p l o t ( xs , p s i * p s i )
47 pylab . xlim ( xmax=x_max , xmin=x_min )
48 pylab . x l a b e l ( " $x$ " , s i z e =18)
49 pylab . y l a b e l ( " $ \ psi_ {" + s t r ( n ) + " } ( x ) $ " , s i z e =18)
50 pylab . t i t l e ( " Quantum Harmonic O s c i l l a t o r Wavefunction ( $n = " + s t r ( n ) + "$ ) " , s i z e =14)
51 pylab . show ( )
8-66 Lecture 8: Python For Teaching Physics-I

KC
Figure 8.18:

SR
Stationary State for HO with the

We have used the natural system of units, wherein, the constants are taken as
C Ψ2 plot.

The Lines 14 and 16 dene the wavefunction with and without the normalization constants.
The square of these quantities are also obtained in the same command.
1.
AE
We also proove that the wavefunction is normalized by obtaining the necessay integral.

8.2.7 Wave Packets


CD

We know that the relation

h
λ =
p

holds true for both photons as well as particles. Hence, it is possible to use concentrated
UG

waves to describe localized particles of matter as well as quanta of radiation, such that
wavefunction depends only on the cordinates (x, y, z) and time (t). If we were to restrict our
discussions to the one-dimensional case, then the wavefunction Ψ depends only on x & t. This
is the closest we shall come in quantum mechanics to making a particle behave classically.
We know that
Z +∞
1 ~k2
Ψ(x, t) = √ φ(k)ei(kx− 2m t) dk
2π −∞

carries a range os k0s and hence is aptly referred to as wave packet.


Lecture 8: Python For Teaching Physics-I 8-67

Since, we would be discussing, at t=0 , either the co-ordinate wavefunction Ψ(x, 0) or the
momentum wavefunction Φ(p, 0), both of which are Fourier Transform of each othe (refer
Appendix), such that

Z +∞
1
Ψ(x, 0) = √ φ(k)eikx dk
2π −∞
then
Z +∞
1
Φ(k) = = √ φ(x, 0)eikx dk
2π −∞

KC
The simplest version of a wavepacket consists of a momentum eigenfunction multiplied by
an envelope function, which has a substantial amplitude in the central region and decreases
rapidy, so as to smoothen out on the either side. We immediately recognize this to be the
blue, Gaussian function (inverted bell shaped). Refer the Appendix for some details.

C SR
If the wavepacket has it's coordinate wavefunction as

Ψ(x) = Ae −
(x−x0 )2
a2 e
ip0 x
~

Then the momentum space wavefunction is obtained from the Fourier transform (refer Ap-
pendix), as
AE
(p−p0 ) 2
Ψ̃(p) = Be−a( 2~
)

Now let us consider a particle that is localized in space and t = 0. It would be represented
CD

by a Gaussian distribution,

A x2
Ψ(x) = √ e− 2σ2
2πσ 2

We shall expand the given wavefunction, into plane waves, which is achieved by taking the
UG

Fourier Transform.

Then we shall let each plane wave evolve in time, as Ψ(x) = e−i(kx−ωt) . We shall consider
natural units, where ~ = 1 , and m = 1.
The code below, allows us to probe the time evolution of the gaussian wave packet. We shall
gradually build up the entire code. As a rst step, we need to create the wave packet, as
shown in Fig. 8.19
8-68 Lecture 8: Python For Teaching Physics-I

Generate a Gaussian packet

1 import numpy as np
2 from scipy . stats import norm
3 import matplotlib . pyplot as plt
4 from math import e
5 import cmath
6 import time
7
8 N = 201

KC
9 mu, s i g m a = 0. ,2.0
10
11 x = np . l i n s p a c e ( - 1 0 0 , 1 0 0 , 2 0 1 )
12 dx = x [ 2 ] - x[1]
13
14 dist = norm (mu, sigma )
15
16
17
18
19
20
A = d i s t . pdf ( x )
B = A/ np . l i n a l g . norm (A)

p l t . p l o t ( x , B)
C
plt . xlabel ( 'x ')
plt . grid ()
SR
21 plt . ylabel ( ' $\ Psi ( x ) $ ' )
AE
22 p l t . show ( )
CD
UG

Figure 8.19: Gaussian packet.

Now, if we were to perform a Fourier transform of the above function, would result is expand-
Lecture 8: Python For Teaching Physics-I 8-69

ing it into plane waves, in k space. Now, we know that Fourier transform, is a mathematical
tool to provide a mapping from the time domain to frequency domain.

We shall use the Fast Fourier Transform , a technique to achieve the that Fourier Transform
in an numerically ecient manner. We shall use the t function provided in numpy.

It is observed that we usually use a combination of t and tshift commands in a combination.


The t command is used to perform the maths, and tshift is used for conviniently plotting.
The code, below achieves, the FFT of the given Gaussian packet, and the results are presented
in Fig. 8.20.

KC
FFT for the given gaussian packet
1
2
3
4
5
6
7
8
9
10
11
12
13
C import numpy a s np
from s c i p y . s t a t s import norm
import m a t p l o t l i b . p y p l o t as p l t
from math import e
import cmath
import time
N = 201
mu, sigma = 0 . , 2 . 0
x = np . l i n s p a c e ( - 1 0 0 , 1 0 0 , 2 0 1 )
dx = x [ 2 ] - x [ 1 ]
K=np . z e r o s (N)
KK=np . z e r o s (N)
SR
14
AE
15 f o r i i n r a n g e ( l e n (K ) ) :
16 K[ i ]= i
17
18 d i s t = norm (mu, sigma )
19 A = d i s t . pdf ( x )
20 B = A/np . l i n a l g . norm (A)
21
22 Y= np . f f t . f f t s h i f t ( np . f f t . f f t (B) )
23
CD

24 f o r i i n r a n g e ( l e n (K ) ) :
25 i f (K[ i ] > N/ 2 ) :
26 K[ i ] = K[ i ] -N
27
28 K=np . f f t . f f t s h i f t (K)
29
30 p l t . p l o t (K,Y. r e a l , l a b e l =' Real ' )
31 p l t . p l o t (K,Y. imag , l a b e l ='Imag ' )
32 p l t . p l o t (K, np . abs (Y) , l a b e l ='Abs ' )
33 p l t . t i t l e ( ' Wave i n K- space ' )
34 plt . legend ()
35 plt . xlabel ( 'x ')
UG

36 plt . grid ()
37 p l t . y l a b e l ( 'Y' )
38 p l t . show ( )

Now, we would like to conrm the operation, by reconstructing the original packet, using
the Fourier Coecients, at t = 0. We just add the following lines, to the above already
developed Python code.
8-70 Lecture 8: Python For Teaching Physics-I

KC
Figure 8.20:
C SR
FFT of the Gaussian packet, equivalent to expanding it into plane waves.
AE

Reconstruction of the gaussian packet from FFT

1 PlaneWave= complex ( 0 , 0 )
CD

2 PlaneWave1= complex ( 0 , 0 )
3 temp= complex ( 0 , 0 )
4 Wave=np . z e r o s (N, d t y p e=np . c o m p l e x 1 2 8 )
5 Wave1=np . z e r o s (N, d t y p e=np . c o m p l e x 1 2 8 )
6 Wave2=np . z e r o s (N, d t y p e=np . c o m p l e x 1 2 8 )
7
UG

8 for kk i n r a n g e ( 1 ,N ) :
9 KS=K[ kk ]
10 KWV=2* np . p i *KS
11 temp=KWV
12 for n in r a n g e ( l e n (K ) ) :
13 PlaneWave = ( 1 . 0 /N) * ( cmath . exp ( complex ( 0 , ( temp * n/N ) ) ) )
14 Wave [ n]=Wave [ n]+Y [ kk ] * PlaneWave
15
16 p l t . p l o t ( x , Wave . r e a l )
17 p l t . show ( )
Lecture 8: Python For Teaching Physics-I 8-71

Now, we track the time evolution of this wavepacket, using the following code

FFT for the given gaussian packet


1 import numpy a s np
2 from s c i p y . s t a t s import norm
3 import m a t p l o t l i b . p y p l o t as p l t
4 from math import e
5 import cmath
6 import time
7
8 N = 201
9 mu, sigma = 0 . , 2 . 0
10 x = np . l i n s p a c e ( - 1 0 0 , 1 0 0 , 2 0 1 )
11 dx = x [ 2 ] - x [ 1 ]
12 K=np . z e r o s (N)

KC
13 KK=np . z e r o s (N)
14 PlaneWave= complex ( 0 , 0 )
15 PlaneWave1= complex ( 0 , 0 )
16 temp= complex ( 0 , 0 )
17 Wave=np . z e r o s (N, dtype=np . complex128 )
18 Wave1=np . z e r o s (N, dtype=np . complex128 )
19 Wave2=np . z e r o s (N, dtype=np . complex128 )
20
21 f o r i i n r a n g e ( l e n (K ) ) :
22 K[ i ]= i
23

SR
24 d i s t = norm (mu, sigma )
25 A = d i s t . pdf ( x )
26 B = A/np . l i n a l g . norm (A)
27
28 Y= np . f f t . f f t s h i f t ( np . f f t . f f t (B) )
29
30 f o r i i n r a n g e ( l e n (K ) ) :
31 i f (K[ i ] > N/ 2 ) :
32 K[ i ] = K[ i ] -N
33
C
34 K=np . f f t . f f t s h i f t (K)
35
36 f o r kk i n r a n g e ( 1 ,N ) :
37 KS=K[ kk ]
38 KWV=2*np . p i *KS
39 temp=KWV
AE
40 f o r n i n r a n g e ( l e n (K ) ) :
41 PlaneWave = ( 1 . 0 /N) * ( cmath . exp ( complex ( 0 , ( temp*n/N) ) ) )
42 Wave [ n]=Wave [ n]+Y[ kk ] * PlaneWave
43
44 t =0.001
45 sum = 0 . 0
46 f o r kk i n r a n g e ( 1 ,N ) :
47 KS=K[ kk ]
48 KWV=2*np . p i *KS
CD

49 W= 1 . 0 / 2 . 0 *KWV**2
50 temp1 = KWV
51 f o r n i n r a n g e ( 1 ,N ) :
52 PlaneWave1 =(Y[ kk ] /N) * ( cmath . exp ( complex ( 0 , ( ( ( temp1/N) * n ) -W* t ) ) ) )
53 Wave1 [ n]=Wave1 [ n]+ PlaneWave1
54 Wave2 [ n]= Wave1 [ n ] * * 2
55 sum = sum +np . abs ( Wave2 [ n ] )
56 p r i n t sum
57 p l t . p l o t ( x , np . abs ( Wave2 ) , l a b e l =' t = 0 . 0 0 0 0 1 ' )
58 p l t . show ( )
UG

The wavefunction for two representative values of time t , are presented in Fig. 8.21.

We can see that as time increases, the x expectation value remains constant, however σ
increases and the wave packet spreads in space. However, the net area under the curve
in all the cases (represented by the variable sum) is identical. Kindly note the y-axis labels,
in both the gures, as time progresses, the amplitude of the wavepacket decreases to conserve
the net area.
8-72 Lecture 8: Python For Teaching Physics-I

KC
C SR
AE

Figure 8.21: Time evolution of the gaussian packet.


CD
UG

You might also like