Share 'Python Notes2013 (Old) .PDF'
Share 'Python Notes2013 (Old) .PDF'
S STUDENTS
V.N.Purushothaman
Department of Physi s
31-03-2013
2
Contents
1.2 Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.11 Pi kling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.12 Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3
4 CONTENTS
4 Numeri
al Analysis 61
4.1 Numeri
al methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5 Simulations 89
5.1 A
omputational approa
h to physi
s . . . . . . . . . . . . . . . . . . . 89
Prefa e
This is a rough
olle
tion of the le
ture notes I had prepared to tea
h the
ourse
PHY2C08: COMPUTATIONAL PHYSICS pres
ribed for M.S
physi
s students of
olleges aliated to Cali
ut University. Due to la
k of time, it is done at a terri
pa
e
whi
h might have
aused a few mistakes here and there. Shortage of explanations and
examples is another
asualty of su
h hurry. I hope that it may be useful in some small
way to students and tea
hers. Please be kind enough to inform me when you
ome
a
ross mistakes in the ideas or language used in this monograph. Purushothaman.V.N,
Department of Physi
s,
Sree Kerala Varma College, Tri
hur
email:vadakkedamredimail.
om
Mob: 9446723810
ii CONTENTS
Chapter 1
1.1 Inputs
A program is a set of statements used to produ
e an output from the input data.
Numbers (real and
omplex), are read from terminal using the fun
tion input('Prompt')
. Strings are read using the fun
tion raw_input('prompt'). For example
1.2 Outputs
The output of a program
an be a number, text or graphi
s. For text and numbers print
statement is employed. For graphi
output fun
tions like show(),saveg(),imshow() et
are dened in relevant modules.
>>> x=5
>>> print x
1
2 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
5
>>> y=[2,5,7,9℄
>>> print y
[2, 5, 7, 9℄
>>> z='beamer'
>>> print z
beamer
>>> print x,y,z
5 [2, 5, 7, 9℄ beamer
Formatted output is possible just as in
-language. The general form of format string
is %m.nx where m is an integer showing the total width to be used for printing, n is
an integer representing the number of de
imal pla
es to be used while printing oating
point numbers so that |m| ≥ 1 + n(de
imal point+de
imal pla
es) and x is c for single
hara
ter, f for oat, e for oat in s
ienti
format, s for string, x for hexade
imal, o
for o
tal, d or i for integer and 0d for integer with zeros on the left to ll the width.
1.4 operators
Bitwise operator works on bits and perform bit by bit operation. Assume a = 60 and
b = 13. Now in binary format they will be as follows:
a = 0011 1100,
b = 0000 1101
Binary AND Operator
opies a bit to the result if it exists in both operands.
a&b = 0000 1100
Binary OR Operator
opies a bit if it exists in either operand.
a|b = 0011 1101
Binary XOR Operator
opies the bit if it is set in one operand but not both.
a^b = 0011 0001
Binary Ones Complement Operator is unary and has the effe
t of 'flipping' bits.
~a = 1100 0011
Binary Left Shift Operator moves left operand by the number of bits spe
ified by the
a << 2 will give 1111 0000 whi
h is 240
Binary Right Shift Operator moves left operand by the number of bits spe
ified by th
a >> 2 will give 0000 1111whi
h is 15
Pre
eden
e Rules of operators: These rules give the sequen
e of exe
utions of an
expression
ontaining more than one operator.
4 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
3. -x, +x (unary ±)
7. logi al not
8. logi al and
1.5 Strings
There is one major dieren
e between String, tuple, list,di
tionary types. List and
di
tionary are mutable but string and tuple are immutable. We
an
hange the value
of an element in a list , add new elements to them and remove any existing element.
This is not possible with String and tuple types.In the
ase of sets one variety
alled
frozenset is immutable while set is mutable.
List
List is mu
h more exible than String. The individual elements
an be of any type,
even another list. Lists are dened by en
losing the elements inside a pair of square
bra
kets and separated by
ommas.
>>> l=[2.3,'A',3,'khan'℄
>>> type(l)
<type 'list'>
>>> 2*l
[2.29, 'A', 3, 'khan', 2.29, 'A',3, 'khan'℄
>>> l[3℄=28
>>> l
[2.299, 'A', 3, 28℄
List Methods
A method is a fun
tion that is
oupled to some obje
t, be it a list, a number, a string,
or whatever. In general, a method is
alled like this: obje
t.method(arguments). If a
is list obje
t and max() is a method dened on list
lass to nd the maximum value
in the list, then a.max() returns maximum of list a. A method
all is like a fun
tion
6 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
all, ex
ept that the obje
t is put before the name of the method method with a dot
separating them. Lists have several methods that
an be used to examine or modify
their
ontents.
1. append: The append method is used to append an obje
t to the end of a list:
>>>lst = [1, 2, 3℄
>>>lst.append(4)
>>>lst
>>>[1,2, 3, 4℄
4. index: The index method is used for sear
hing lists to nd the index of the
rst o
urren
e of a value:
When you sear h for the word 'who', you nd that it's lo ated at index 4:
>>> knights[4℄
'who'
5. insert: The insert method is used to insert an obje
t into a list: > numbers
= [1, 2, 3, 5, 6, 7℄ > numbers.insert(3, 'four') > numbers > [1, 2, 3, 'four', 5,
6, 7℄ As with extend, you
an implement insert with sli
e assignments:
numbers = [1, 2, 3, 5, 6, 7℄
numbers[3:3℄ = ['four'℄
numbers
[1, 2, 3, 'four', 5, 6, 7℄
6. pop: The pop method removes an element (by default, the last one) from the
list and returns it:
>>> x = [1, 2, 3℄
>>> x.pop()
>>> x
>>> [1, 2℄
>>> x.pop(0)
>>> x
>>> [2℄
The pop method is the only list method that both modies the list and returns
a value.
>>> x = [1, 2, 3℄
>>> x.append(x.pop())
>>> x
>>> [1, 2, 3℄
7. remove: The remove method is used to remove the rst o
urren
e of a value:
8 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
8. del: To remove a list element, you
an use either the del statement if you know
exa
tly whi
h element(s) you are deleting or the remove() method if not known.
The reverse method reverses the elements in the list.
> x = [1, 2, 3℄ > x.reverse() > x > [3, 2, 1℄ Note that reverse
hanges the
list and and saves under the same name. > x = [1, 2, 3℄ > list(reversed(x)) [3,
2, 1℄
9. sort: The sort method is used to sort lists in pla
e. Sorting 'in pla
e' means
hanging the original list so its elements are in sorted order, rather than simply
returning a sorted
opy of the list:
>>> x = [4, 6, 2, 1, 7, 9℄
>>> x.sort()
>>> x
>>> [1, 2, 4, 6, 7, 9℄
>>> x = [4, 6, 2, 1, 7, 9℄
>>> x.sort(reverse=True)
>>> x
>>> [9, 7, 6, 4, 2, 1℄
10. sorted: Another way of getting a sorted
opy of a list is using the sorted
fun
tion :
>>> x = [4, 6, 2, 1, 7, 9℄
>>> y=sorted(x)
>>> x,y
([4, 6, 2, 1, 7, 9℄, [1, 2, 4, 6, 7, 9℄)
This fun tion an a tually be used on any sequen e, but will always return a list:
>>> sorted('Python')
>>> ['P', 'h', 'n', 'o', 't', 'y'℄
13. min: Gives the element having minimum ASCII value in a list.
14.
mp: This fun
tion is the basis for sorting.
mp(a, b) returns -1 if a < b, 0 if a
== b and 1 if a > b.
15. list: Converts a string or tuple into a list.
16. sum: Returns the sum of elements in a numeri
list.
For example
>>> a=[2,5,'A','a','ab'℄
>>> max(a)
'ab'
>>> a.append('z')
>>> a
[2,5,'A','a','ab','z'℄
>>> max(a)
'z'
>>> min(a)
2
>>> x=[4, 7, 8, 2, 3, 12℄
>>>
mp(a,x)
-1
>>>
mp(x,a)
1
>>> y=x
>>> y
[4, 7, 8, 2, 3, 12℄
>>>
mp(x,y)
0
>>>
='design'
>>> list(
)
['d', 'e', 's', 'i', 'g', 'n'℄
>>> d=('j','k',3,5)
>>> list(d)
['j', 'k', 3, 5℄
>>> sum(x)
36
Sli
ing: Elements from a list
an be sele
ted using sli
ing operator ':'. If x is a list,
then x[m : n : p] represents the set of elements of x with indi
es [mth , (m + p)th , (m +
2p)th , ..] ex
luding nth element.
10 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
>>> x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9℄
>>> x[0:-1:2℄
[0, 2, 4, 6, 8℄
>>> x[1:-1:2℄
[1, 3, 5, 7℄
>>> sum(x[1:-1:2℄)
16
>>> x[0:5:2℄
[0, 2, 4℄
>>> sum(x[0:5:2℄)
6
set:
A set obje
t is an unordered
olle
tion of immutable values. They
annot be indexed
by any subs
ript. The built-in fun
tion len() returns the number of items in a set.
There are
urrently two intrinsi
set types:
(1)Sets: These represent a mutable set. They are
reated by the built-in set()
onstru
tor and
an be modied afterwards by several methods, su
h as add(),
lear(),
dis
ard().
Frozen sets: These represent an immutable set. They are
reated by the built-in
frozenset()
onstru
tor. As a frozenset is immutable, it
an be used as an element
of another set, or as a di
tionary key. Common uses of sets in
lude membership
testing, removing dupli
ates from a sequen
e, and
omputing mathemati
al operations
su
h as interse
tion, union, dieren
e, and symmetri
dieren
e. The main fun
tions
are len(), union(), interse
tion(), dieren
e(), symmetri
_dieren
e(), issubset() and
issuperset(). There is also an operator equivalent for many of these fun
tions. Let s
and t be two sets. Then
8. s.symmetri
_dieren
e(t) : [s t℄: new set with elements in either s or t but not
both
11. s.dis
ard(x): Remove element x from set s if it is a member. If x is not a member,
nothing happens.
>>> a=[1,2.0,6.1,'l'℄
>>> b=set(a)
>>> b
set([1, 2.0, 'l', 6.0999999999999996℄)
>>>
=set([1,3,6.1,'k'℄)
>>>
set([1, 'k', 3, 6.0999999999999996℄)
>>> d=set('domain')
>>> d
set(['a', 'd', 'i', 'm', 'o', 'n'℄)
>>> f=set((1,3,5,9.1))
>>> f
set([1, 3, 9.0999999999999996, 5℄)
>>> b|
set([1, 2.0, 3, 'k', 'l', 6.0999999999999996℄)
>>> b&
set([1, 6.0999999999999996℄)
>>> b.differen
e(
)
set([2.0, 'l'℄)
>>>
.differen
e(b)
set(['k', 3℄)
>>>
.symmetri
_differen
e(b)
set(['k', 2.0, 3, 'l'℄)
>>> s=set([1,3,5,7,9℄)
>>> s.add(11)
>>> s
set([1, 3, 5, 7, 9, 11℄)
>>> s.remove(5)
>>> s
set([1, 3, 7, 9, 11℄)
12 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
Tuples
Tuples are data stru
tures that are very similar to lists, but they
annot be modied
(immutable). They
an only be
reated. Tuples have important roles as keys for
di
tionaries. A tuple is a sequen
e that is en
losed by parentheses ( ). The following
line of
ode
reates a three-element tuple
Inter onversion between lists and tuples is possible using list() and tuple() fun tions.
Di tionaries
Di
tionaries are asso
iative arrays. It is a group of {key : value} pairs. The elements
in a di
tionary are indexed by keys. Keys in a di
tionary are required to be unique.
Keys
an be almost any Python type, but are usually numbers or strings. Values, on
the other hand,
an be any arbitrary Python obje
t. Di
tionaries are en
losed by
urly
bra
es - { } and values
an be assigned and a
essed using square bra
es [℄. They are
dierent from sequen
e type
ontainers like lists and tuples in the method of storing
data. There is no
on
ept of order among elements. They are unordered.Their main use
in
lude storing time of modi
ation of les as values and le name as keys, telephone
dire
tory with name as value and phone number as key, address book with name as key
and address as value, the
oordinate of a point(tuple) as key and its
olour as value in
a graphi
s
reen et
. Example for a di
tionary is given below.
['host', 'port'℄
>>> d
t.values()
['Earth', 80℄
>>> print d
t['host'℄
2. len(di
t): Gives the total length of the di
tionary. This would be equal to the
number of Key-value pairs in the di
tionary.
3. di
t.fromkeys(): Create a new di
tionary with keys from seq and values set to
value.
4. di
t.get(key, default=None): For key key, returns value or default if key not in
di
tionary
The most fundamental aspe
t of a programming language is the ability to
ontrol the
sequen
e of operations. One of this
ontrol is the ability to sele
t one a
tion from a set
of spe
ied alternatives. The other one is the fa
ility to repeat a series of a
tions any
number of times or till some
ondition be
omes false. To exe
ute some se
tion of the
ode only if
ertain
onditions are true python uses if, elif,...,else
onstru
t.
when a
ondition remains true, if a set of statements are to be repeated, the while
and for
onstru
ts are employed. The general syntax of a while loop may be given as
follows.
while
ondition:
set of statements to be repeated
for elements in list or tuple :
set of statements to be repeated
>>> x=10
>>> while x>0:
print x,
x=x-1
>>>10 9 8 7 6 5 4 3 2 1
>>> for i in range(10,0,-1):
print i,
>>>10 9 8 7 6 5 4 3 2 1
1.9. FUNCTIONS AND MODULES 15
A fun
tion is a blo
k of
ode that performs a spe
i
task. Using a fun
tion in a
program is
alled '
alling' the fun
tion. Python has two tools for building fun
tions:
def and lambda. For example, we
an build a fun
tion that returns the square root of
a number as follows:
(1) def squareroot(x): return math.sqrt(x)
(2) squareroot = lambda x: math.sqrt(x)
(3) g = lambda x: x*2
g(3)=6
(4) (lambda x: x*2)(3)= 6
If a fun
tion is used only on
e (
alled from only one pla
e in your program) Lambda
fun
tions are useful and
onvenient for two reasons: (1)There is no need to give the
fun
tion a name.(2) It
an be dened where it is used.
The next method of dening fun
tions is illustrated below. For nding the largest
of x,y,z
In Python, the denitions of fun
tions, variables,
onstants may be saved in a le
and use them in a s
ript or in an interpreter just like header les in C-language.
Su
h a le is
alled a module. The le name is the module name with the sux .py
appended. Within a module, the name of the module is assigned to the global variable
_name_. Denitions from a module
an be imported into other modules or into the
main module. Examples of some standard modules are math, os,random, pylab, numpy
et
. The main advantage of
reating and using modules is that longer programs
an
be split into several les so that maintenan
e of
ode is easy and
an be reused in
several programs by in
luding the le with the keyword import at the beginning of the
program.
16 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
Files are used to store data and program for later use. This program
reates a new le
named 't.txt' (any existing le with the same name will be deleted) and writes a String
to it. The le is
losed and then reopened for reading data. The relevant fun
tions are
open, write, read and
lose.
>>> f=open('t.txt','w')
>>> f.write('breaking into the file')
>>> f.
lose()
>>> f=open('t.txt','r')
>>> f.read()
'breaking into the file'
1.11 Pi kling
Strings
an easily be written to and read from a le. Numbers take more eort,
sin
e the read() method only returns strings, whi
h will have to be
onverted into a
number expli
itly. However, it is very
ompli
ated when trying to save and restore
data types like lists, di
tionaries et
. Rather than
onstantly writing and debugging
ode to save
ompli
ated data types, Python provides a standard module
alled pi
kle.
Fun
tions dump and load are used in pi
kle. pi
kle.dump(a,f ) will save obje
t a to le
f. a=pi
kle.load(f ) retrieves data from le f.
Pi kling- Examples
>>>import pi
kle
>>>a=10.1
>>>b='sh'
>>>
=[5,3,2℄
>>>f = open("state", 'w')
>>>pi
kle.dump(a, f)
pi
kle.dump(b, f)
pi
kle.dump(
, f)
file.
lose()
a = pi
kle.load(file)
b = pi
kle.load(file)
= pi
kle.load(file)
file.
lose()
1.12 Problems
a=[℄
n=input('Give the
ount of numbers n')
for i in range(n):a.append(input('Type the numbers'))
a.sort() #As
ending order
print a
a.reverse() # Des
ending order
print a
Program:
from math import *
x=[sin(2*pi*i/100) for i in range(1,101)℄
y=[
os(2*pi*i/100) for i in range(1,101)℄
print x,y
Program:
n=input('Howmany rows ? ')
for i in range(n):
print
for j in range(i+1): print '*',
Howmany rows ? 7
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
4. Fibona i series:
import math
x=[0.1*i for i in range(10)℄
1.12. PROBLEMS 19
y=[i*math.sin(i) for i in x℄
for i in range(10):
print '(%0.2f,%0.5f)'%(x[i℄,y[i℄),
8. Permutations
def
ombination(n,r):
if r==0:return 1
else:return n*
ombination(n-1,r-1)/r
n,r=input('Give n and r in nCr: ')
print
ombination(n,r)
Aliter:
def f(a):
if a==1:return(1)
else: return(a*f(a-1))
n,r=input('Give n and r in nCr: ')
print f(n)/(f(n-r)*f(r))
Pin
iple: It is the set of binomial
oe
ients arranged in rows. The, nth row
orresponds to the
oe
ients of the expansion (a + b)n
def f(a):
if a==0:return(1)
else: return(a*f(a-1))
n=input('Howmany rows ? ')
for i in range(n):
print
for j in range(i+1): print f(i)/(f(i-j)*f(j)),
Aliter:
def
ombination(n,r):
if r==0:return 1
else:return n*
ombination(n-1,r-1)/r
m=input('Howmany rows ? ')
for i in range(m+1):
print
for j in range(i+1):print
ombination(i,j),
Howmany rows ? 7
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
where n = 0, 1, 2, 3...
Program:
m=input('Give maximum number upto whi
h the series is required: ')
print [i*(i+1)/2 for i in range(m) if i*(i+1)/2 < m℄
Aliter :
The relation between adja
ent elements is
n,a=input('n: '),0
for i in range(n):
a+=i
print a
Prin
iple: Pi
k any whole number. If it's odd, multiply the number by 3, then
add 1. If it's even, divide it by 2. Now, apply the same rules to the answer that
you just obtained. Do this over and over again, applying the rules to ea
h new
answer. Hen
e these are the set of numbers obtained by the following rule of
iteration.
If si is even, si+1 = si /2, else si+1 = 3si + 1
Program:
s=input('Seed number for Hailstorm series: ')
while s!=1:
if s%2==0:s/=2
else:s=(3*s+1)
print s,
22 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
x=[℄
n=input('Give the
ount of numbers')
for i in range(n): x.append(input('Type numbers one at a time '))
print 'Largest of the series is',max(x)
print 'Smallest of the series is',min(x)
Prin
iple: Even numbers
annot be prime. Che
k in the set of odd numbers
for prime numbers.
j,k=input("Give the range between whi
h prime numbers are required: ")
x=range(j,k,1)
p=[℄
for n in x:
m=n/2
if n>0 and n<4:p.append(n)
for i in range(2,m+1):
if n%i==0: break
if i==m: p.append(n)
print 'There are %d prime numbers in the range(%d, %d). They are'%(len(p),j,k)
print p
When the program is run
Give the range between whi
h prime numbers are required: 49,150
There are 20 prime numbers in the range(49, 150). They are
[53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101,
103, 107, 109, 113, 127, 131, 137, 139, 149℄
18. To
he
k whether a given word is a palindrome.
24 CHAPTER 1. UNIT-1: BASICS OF PYTHON LANGUAGE
Prin
iple: A sequen
e is a palindrome if it is the same when read from left or
right. For example, xyzzyx,123321 are palindromes.
Program:
x=raw_input('Give the word')
y=[x[-i-1℄ for i in range(len(x))℄
if list(x)==y:print 'palindrome'
else: print 'Not a palindrome'
Prin
iple: Let x be the square root of n. Then x2 − n = 0. Now x is the root
of this equation. It
an be
al
ulated using Newton-Raphson method.
f (x) = x2 − n, f ′ (x) = 2x
f (xk ) 1 n
xk+1 = xk − ′ = xk +
f (xk ) 2 xk
Program:
n,e=input('Give the number n and a
ura
y required e: ')
x0,x=0,1
while abs(x-x0)>e:
x0=x
x=(x0+n/x0)/2.0
print 'Square root of %0.3f =%0.5f '%(n,x0)
Prin
iple: Let x be the mth root of n. Then xm − n = 0. Now x is the mth
root of this equation. It
an be
al
ulated using Newton-Raphson method.
Program:
Program:
Prin
iple: The value of π
an be
al
ulated using tan 45o = tan (π/4) = 1 as
follows.
∞
X (−1)i
π 1 1 1
= tan−1 1 = 1 − + − + ....... =
4 3 5 7 i=0
2i + 1
Program:
Python keywords
2.1 NumPy
NumPy's main
lass is the homogeneous multidimensional array
alled ndarray. This
is a table of elements (usually numbers), all of the same data type. Ea
h element
is indexed by a tuple of positive integers. Examples of multidimensional array ob-
je
ts in
lude ve
tors, matri
es, spreadsheets et
. The term multidimensional refers to
arrays having several dimensions or axes. The number of axes is often
alled rank
( not a tensor rank).
For example, the
oordinates of a point in 3-D spa
e (x, y, z) is an array of rank
1. This also gives the position ve
tor of that point.
The array ([1., 0., 0.], [0., 1., 2.])
1 0 0
is one of rank 2. It is equivalent to (it is 2-dimensional). The rst
0 1 2
dimension (rows) has a length of 2, the se
ond dimension(
olumn) has a length of 3.
(1 0) 0
The array ([[1., 0.], 0.], [[0., 1.], 2.]) is one of rank 3. It is equivalent to (it
(0 1) 2
is 3-dimensional).
There are many ways to
reate arrays. For example, you
an
reate an array from a
regular Python list or tuple using the array fun
tion.
29
30 CHAPTER 2. ADVANCED PYTHON PROGRAMMING
The fun
tion array() transforms sequen
es of sequen
es into two-dimensional arrays,
and it transforms sequen
es of sequen
es of sequen
es into three-dimensional arrays,
and so on. The type of the resulting array is dedu
ed from the type of the elements in
the sequen
es.
To
reate an array whose elements are sequen
es of numbers, NumPy provides a fun
-
tion arange(x1 , x2 , dx) and returns x1 , x1 + dx, ...., x2 − dx. It is analogous to range
fun
tion but a
epts oating point numbers also.
array and arange are not the only fun
tions that
reate arrays. Usually the elements
of the array are not known from the beginning, and a pla
eholder array(empty array)
is needed. There are some fun
tions to
reate arrays with some initial
ontent. By
default, the type of the
reated array is oat64. The fun
tion zeros((m,n))
reates a
2-D array of m rows and n
olumns with zeros as elements. Similarly the fun
tion
ones((m,n))
reates an array full of ones, the fun
tion empty((m,n))
reates an array
without lling it in and the fun
tion random((m,n))
reates an array lling it with
random numbers between 0 and 1. identity (n)
reates an n-dimensional unit matrix.
Then the initial
ontent is random and it depends on the state of the memory. In these
fun
tions the arguments m, n spe
ies the size along ea
h axis of the array.
Using arange with oating point arguments, it is generally not possible to predi
t
the number of elements obtained be
ause of the oating point pre
ision. Hen
e it is
better to use the fun
tion linspace(x1 , x2 , nx) whi
h returns equispa
ed nx numbers
from x1 to x2 .
2.1. NUMPY 31
The general syntax of these fun
tions are empty (shape=, dtype=int) Return an
uninitialized array of data type, dtype, and given shape.
An array of zeros
an be
reated with a spe
ied shape using zeros() fun
tion.
zeros(shape=, dtype=) :Return an array of data type dtype and given shape lled with
zeros. An array of ones
an be
reated with a spe
ied shape using ones() fun
tion.
zeros(shape=, dtype=) : Return an array of data type dtype and given shape lled with
zeros. an identity matrix
an be
reated using identity() fun
tion
identity (n, dtype=int) : Return a 2-d square array of shape (n,n) and data type, dtype
with ones along the main diagonal.
>>> empty( (2,3) ) # the
ontent may
hange in different invo
ations
array([[ 3.14678735e-307, 6.02658058e-154, 6.55490914e-260℄,
[ 5.30498948e-313, 3.73603967e-262, 8.70018275e-313℄℄)
>>> a=identity(4,dtype=float)
>>> a
array([[ 1., 0., 0., 0.℄,
[ 0., 1., 0., 0.℄,
[ 0., 0., 1., 0.℄,
[ 0., 0., 0., 1.℄℄)
>>> linspa
e( 0, 2, 9 )
array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ℄)
>>> x = linspa
e( 0, 2*pi, 10 )
>>> x
32 CHAPTER 2. ADVANCED PYTHON PROGRAMMING
Array attributes
6. b.data : Returns the buer ontaining the a tual elements of the array.
The type of the array an also be expli itly spe ied at reation time:
A frequent error
onsists in
alling array with multiple numeri
arguments, rather than
providing a single list of numbers as an argument.
[ 6, 7, 8℄,
[ 9, 10, 11℄℄)
>>> a
array([[ 0, 1, 2℄,
[ 3, 4, 5℄,
[ 6, 7, 8℄,
[ 9, 10, 11℄℄) # Permanent
hange to shape
>>> a.transpose()
array([[ 0, 3, 6, 9℄,
[ 1, 4, 7, 10℄,
[ 2, 5, 8, 11℄℄) # No permanent
hange to shape
The reshape fun
tion returns its argument with a modied shape, whereas the resize
method modies the array itself:
When you print an array, NumPy displays it in a similar way to nested lists, but with
the following layout:
3. and the rest, also from top to bottom, separating ea h sli e by an empty line.
One dimensional arrays are then printed as rows, two dimensional as matri
es and
three dimensional as lists of matri
es.
>>> a = arange(6)
>>> print a
[0 1 2 3 4 5℄
>>>
>>> b = arange(12).reshape(4,3)
>>> print b
[[ 0 1 2℄
[ 3 4 5℄
[ 6 7 8℄
[ 9 10 11℄℄
>>>
2.1. NUMPY 35
>>>
= arange(24).reshape(2,3,4)
>>> print
[[[ 0 1 2 3℄
[ 4 5 6 7℄
[ 8 9 10 11℄℄
[[12 13 14 15℄
[16 17 18 19℄
[20 21 22 23℄℄℄
If an array is too large to be printed, NumPy automati
ally skips the
entral part of
the array and only prints the
orners:
The simplest way to store arrays is to write it to a text le as text using the numpy
fun
tion savetxt(). The array
an be retrieved using the fun
tion genfromtxt(). The
syntax of these fun
tions are
savetxt(fname,array,fmt= ,delimiter=)
Here fname is the name of the le to be
reated and opened for writing, array is the
name of the array, fmt is the format spe
i
ation of the data to be stored, delimiter is
the
hara
ter used to distinguish elements of the array.
>>> b
36 CHAPTER 2. ADVANCED PYTHON PROGRAMMING
When f1.txt and f2.txt are opened in a text editor, the
ontents of the file
f1.txt
0.000000 &1.000000 &2.000000 &3.000000
4.000000 &5.000000 &6.000000 &7.000000
8.000000 &9.000000 &10.000000&11.000000
12.000000&13.000000&14.000000&15.000000
f2.txt
0.0000 1.0000 2.0000 3.0000
4.0000 5.0000 6.0000 7.0000
8.0000 9.0000 10.0000 11.0000
12.0000 13.0000 14.0000 15.0000
>>> genfromtxt('f1.txt',dtype='float')
array([[ 0., 1., 2., 3.℄,
[ 4., 5., 6., 7.℄,
[ 8., 9., 10., 11.℄,
[ 12., 13., 14., 15.℄℄)
>>> genfromtxt('f1.txt',skiprows=2)
array([[ 8., 9., 10., 11.℄,
[ 12., 13., 14., 15.℄℄)
If the arrays are too large, saving them in text format
onsumes large volume of
memory. In that
ase they
an be saved in binary format.
>>> b=load('f3.npy')
>>> b
2.1. NUMPY 37
Arithmeti
operators apply elementwise on arrays. A new array is
reated and lled
with the result.
>>> s
array([1, 2, 3, 4, 5℄)
>>> s.sum() #sum of all elements
15
>>> s.prod() # produ
t of all elements
120
>>> s.mean() # Mean of all elements
3.0
>>> s.var() #Varian
e
2.0
>>> s.std() #Standard deviation
1.4142135623730951
One dimensional arrays
an be indexed, sli
ed and iterated over like lists and other
Python sequen
es.
>>> a = arange(10)**3
>>> a
array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729℄)
>>> a[2℄
8
>>> a[2:5℄
array([ 8, 27, 64℄)
>>> a[:6:2℄ = -1000 \# modify elements in a
>>> a[::-1℄ \# reversed a
array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000℄)
>>> for i in a: print i**(1/3.),
nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0
ross produ
t of two ve
tors. outer (x, y)
omputes an outer produ
t of two ve
tors
(zij = xi .yj ). In matrix
lass to
reate matri
es mat method and matrix method
are dened.mat(data, dtype=),matrix(data, dtype=). This data
an be any list, tuple,
string or array . This fun
tion interprets the input as a matrix.
>>> k=arange(15).reshape(3,5)
>>> k
array([[ 0, 1, 2, 3, 4℄,
[ 5, 6, 7, 8, 9℄,
[10, 11, 12, 13, 14℄℄)
>>> dot(k,t)
matrix([[ 30, 80, 130℄,
[ 80, 255, 430℄,
[130, 430, 730℄℄)
>>> t.fill(3)
>>> t
array([[3, 3, 3℄,
[3, 3, 3℄,
[3, 3, 3℄,
[3, 3, 3℄,
[3, 3, 3℄℄)
>>> s=range(1,6)
>>> m= mat(s)
>>> m
matrix([[1, 2, 3, 4, 5℄℄) #The two square bra
kets are there as most of the matri
es
>>> n=matrix(range(1,6))
>>> n
matrix([[1, 2, 3, 4, 5℄℄)
>>> x=[1,2,3℄
>>> y=[3,2,1℄
>>> dot(x,y) # like dot produ
t of ve
tors
10
>>>
ross(x,y) # like
ross produ
t of ve
tors
array([-4, 8, -4℄)
>>> inner([1,2,3℄,[10,100,1000℄)
3210 # 1.10+2.100+3.1000
>>> a=arange(9).reshape(3,3)
>>> b=a.T # another method to find transpose.
>>> a
array([[0, 1, 2℄,
[3, 4, 5℄,
[6, 7, 8℄℄)
>>> b
array([[0, 3, 6℄,
[1, 4, 7℄,
[2, 5, 8℄℄)
>>> inner(a,b) #Ordinary inner produ
t of ve
tors for 1-D arrays (without
omplex
o
produ
t over the last axes.
When operating with arrays of dierent numeri
data types, the type of the resulting
array
orresponds to the more general or pre
ise one.
Many unary operations, like
omputing the sum of all the elements in the array, are
implemented as methods of the ndarray
lass.
>>> a = random.random((2,3))
>>> a
array([[ 0.6903007 , 0.39168346, 0.16524769℄,
2.1. NUMPY 43
By default, these operations apply to the array as if it were a list of numbers, regardless
of its shape. However, by spe
ifying the axis parameter you
an apply an operation
along the spe
ied axis(dimension) of an array:
>>> b = arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3℄,
[ 4, 5, 6, 7℄,
[ 8, 9, 10, 11℄℄)
>>>
>>> b.sum(axis=0) # Give sum as a 1-D array(sum of ea
h
olu
array([12, 15, 18, 21℄)
>>> b.sum(axis=1) # Give sum as a 1-D array(sum of ea
h row)
array([6, 22, 38℄)
>>> b.min(axis=1) # minimum of ea
h row
array([0, 4, 8℄)
>>> b.min(axis=0) # minimum of ea
h
olumn
array([0,1,2,3℄)
>>> p.max(axis=0)
matrix([[12, 13, 14, 15℄℄)
>>> p
matrix([[ 0, 1, 2, 3℄,
[ 4, 5, 6, 7℄,
[ 8, 9, 10, 11℄,
[12, 13, 14, 15℄℄)
>>> tra
e(p)
30
There are four methods dened in polynomial
lass to
reate and manipulate polyno-
mials.
>>>
=[3,1,-1,-3℄
>>> p=poly1d(
)
>>> print p
3 2
3 x + 1 x - 1 x - 3
>>> polyval(p2,2)
23
>>> polyval(p1,2)
-15
2.1. NUMPY 45
>>> polyval(p,2)
23
3. poly(s) : This fun
tion returns the
oe
ients of the polynomial with the s as the
set of roots in the form of an array.
>>> d=[0,0℄
>>> poly(d)
array([1, 0, 0℄) #x*x=0
>>> d=[1,-1,2℄
>>> f=poly(d) #(x-1)(x+1)(x-2)
>>> f
array([ 1, -2, -1, 2℄)
>>> print poly1d(f)
3 2
1 x - 2 x - 1 x + 2
>>> g=[1,-2,-1,2℄
>>> p=poly1d(g)
>>> roots(p)
array([-1., 2., 1.℄)
Roots
an also be found using the following
ommand.
>>> p.r
array([-1., 2., 1.℄)
The linear algebra module is a sub
lass of numpy. It is
alled linalg. A few fun
tions
are dened in the NumPy.linalg sub-pa
kage. The important fun
tions are
6. eig(a) :Returnall solutions (λ, x) to the equation ax = λx. The rst element of
the return tuple
ontains all the eigenvalues. The se
ond element of the return
tuple
ontains the eigenve
tors (ith eigenve
tor as ith
olumn).
1 1 2
Let a be a square matrix −1 0 1. It is
reated as
2 3 0
2x + 3y + 4z = 8, 3x + 4y + 5z = 10, 4x − 5y + 6z = 32
2.1. NUMPY 47
3.1 Matplotlib
Graphs,
harts, surfa
e plots et
are visual presentations of numeri
al data. It is useful
to
ompare,
ontrast, dete
t trends, predi
t and
omprehend huge amounts of data.
Dierent Python modules are used for generating two and three dimensional graphs.
The python pa
kage Matplotlib produ
es graphs and gures in dierent hard
opy for-
mats like jpeg, bmp, eps, png et
. Most of the fun
tions of NumPy and matplotlib.pyplot
are dened in the module pylab also. It also provides many fun
tions for matrix ma-
nipulation. The data for plotting are supplied as Python lists or Numpy arrays. This
module
ontains a lot of methods for plotting and annotating graphs. Some of these
methods are used frequently in s
ienti
omputing. They are listed below with exam-
ples.
49
50 CHAPTER 3. PLOTTING AND VISUALIZATION
9. gure()
num is an integer variable. This fun
tion
reates a new gure if gure(num)
does not exist. If it already exists, it be
omes a
tive. gsize=(w,h) is a tuple
of width and height in in
hes, dpi=N
reates gure with resolution N dots per
square in
h, fa
e
olor sets the ba
kground
olor edge
olor sets the border
olor.
All arguments ex
ept the rst are optional.
13. barh() Like bar() ex ept that the bars are horizontal.
17. semilogx()Graph with x-axis plotted in log s
ale. It supports all the keyword
arguments of plot() fun
tion.
21. Make a polar plot. theta and r are lists or arrays. Multiple
polar(theta, r, args)
theta, r arguments are supported, with format strings, as in plot().
Examples
4.0 4.0
3.5 3.5
3.0 3.0
2.5 2.5
2.0 2.0
1.5 1.5
1.0 1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 0.0 0.5 1.0 1.5 2.0 2.5 3.0
4.0 4.0
3.5 3.5
3.0 3.0
2.5 2.5
2.0 2.0
1.5 1.5
1.0 1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 0.0 0.5 1.0 1.5 2.0 2.5 3.0
Polar plots: Polar
oordinates lo
ate a point on a plane with one distan
e and
one angle. The distan
e `r' is measured from the origin. The angle θ is measured
from positive dire
tion of x-axis in the anti-
lo
kwise sense. Plotting is done using
polar(theta, radius, f ormat string) fun
tion. An example is given below.
90
135 45
1.0
0.8
0.6
0.4
0.2
180 0
225 315
270
Pie Charts: A pie
hart is a
ir
ular
hart in whi
h a
ir
le is divided into se
tors.
Ea
h se
tor visually represents an item in a data set to mat
h the per
entage or fra
tion
of the item in the total data set. Pie
harts are useful to
ompare dierent parts of
a whole amount. They are often used to present nan
ial information. The fun
tion
pie(list of per
entages or fra
tions , labels=list of labels) produ
es a pie
hart. Both
the lists must have the same length.
B+
B A
A+
D
C+
t=arange(0,6.3,0.001)
x=t*
os(t*t)
y=t*sin(t*t)
plot(x,y)
show()
2
4
6
8
6 4 2 0 2 4 6 8
10
15
20
25
0 5 10 15 20 25
3.1. MATPLOTLIB 55
Logarithm fun
tion: Logarithm fun
tion log(x) gives logarithm of a variable to the
base exponential e.
Gaussian fun
tion: Gaussian fun
tion is given by y = exp(−x2 ) gives ex of a vari-
able x.
Gamma fun
tion: The gamma fun
tion is dened by the integral
Z ∞
Γ(x) = tx−1 e−t dt
0
But reasonable a
ura
y
an be a
hieved by just taking the rst ve terms and ap-
proximating elements of a to 2 de
imal pla
es.
120
100
Gamma function
80
60
40
20
0
−4 −2 0 2 4 6
x
58 CHAPTER 3. PLOTTING AND VISUALIZATION
Polynomial Evaluation: Legendre Fun
tion Legendre fun
tions Pn (x) are de-
ned through a generating fun
tion as
∞
1 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
This is a re
urren
e relation whi
h may be used for
al
ulating Legendre polynomials
of any order.
1.0
Legendre Polynomial for n=5 0.5 Bessel function for n=2
0.4
0.5
Legendre function
0.3
Bessel function
0.0
0.2
−0.5
0.1
−1.0 0.0
−1.0 −0.5 0.0 0.5 1.0 −6 −4 −2 0 2 4 6
x x
Polynomial Evaluation: Bessel's Fun
tion The Bessel fun
tion of order n for a
variable x is given by the series
∞
X (−1)s x 2s+n
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.
fa
torial=1
for i in range(1,n+1):fa
torial*=i
term=[z**n/fa
torial℄
for i in range(1,10):
term.append(-term[i-1℄*z*z/(i*(i+n)))
return sum(term)
Numeri al Analysis
Inverse fun
tions are often used in physi
s. For example,
onsider the length L of
the mer
ury
olumn in a
apillary tube as fun
tion of temperature T . L = f (T ).
When it is used as a thermometer, the length of the mer
ury pellet is measured and
the temperature is inferred from it using the formula T = f −1 (L). Similarly, in a
piezoele
tri
rystal, the voltage V developed is a fun
tion of stress S applied. V =
f (S). In a strain gauge, this voltage is measured to estimate the load W pla
ed on
it. W = Af −1 (V ) where A is the surfa
e area of the
rystal on whi
h the load applies
stress. If a fun
tion represents a prin
iple, in general, its appli
ation employs the
inverse fun
tion.
Denition 1 (Fun
tion) For every x in a set X, if an obje
t f maps exa
tly one
element y in set Y then f is
alled a fun
tion with domain X, and
o-domain or range
Y.
It is represented as
∀x ∈ X, y ∈ Y, f : x → y
y is
alled the image and x, the preimage. If there is more than one preimage for a
given image, then f is
alled an onto mapping. For example, f : x → y has the expli
it
form y = x2 , then image y is the same for all ±x in the domain X . If for every image,
there is a unique preimage, f is a one-to-one mapping. For example, f : x → y has
61
62 CHAPTER 4. NUMERICAL ANALYSIS
the expli
it form y = x3 , then image y is the unique for every x in the domain X . In
terms of domain and
o-domain sets f : X → Y .
Denition 2 (Inverse Fun
tion) If f is a fun
tion whose domain is the set X, and
range is the set Y and there exists a fun
tion g with domain Y and range X, with the
property
The fun
tion f sends all elements of the the domain X to the range Y . If f is invertible,
the fun
tion g is unique. There is exa
tly one fun
tion g satises this property. Fun
tion
g is
alled the inverse of f , denoted formally as f −1 . (6= 1/f ). Sin
e f implies unique
y for ea
h x and g implies unique x for ea
h y , the two mappings f and g must be
one-to-one. This is a ne
essary
ondition for f to have an inverse.
100
80
60 onto function
f(x)
40
20
one-to-one function
0
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5
x
Algebrai
method: The algorithm for nding an inverse fun
tion g for f (x) alge-
brai
ally involves the following steps.
2. Put f (x) = y
2. Put 3x + 4 = y
3. Swap variables: 3y + 4 = x
Answer:f −1 (x) = ex
Swapping method: Often the experimental data related through some fun
tion will
be in the form of ordered pairs formed from tables.
x x1 x2 x3 x4 x5 x6 x7 x8 x9
y = f (x) y1 y2 y3 y4 y5 y6 y7 y8 y9
Then f (x) may be expressed as ordered pairs f (x) : (xi , yi )), i = 1, 2, 3... Here
f (x) : (x1 , y1 ), (x2 , y2 ), (x3 , y3 ), (x4 , y4 ), (x5 , y5), (x6 , y6), (x7 , y7 ), (x8 , y8 )(x9 , y9 )
If ∀i, j, xi 6= xj , and yi 6= yj , then the fun
tion f (x) is one-to-one. Its inverse will exist
and
an be obtained by simply swapping x and y values.
f −1 (x) : (y1 , x1 ), (y2, x2 ), (y3 , x3 ), (y4 , x4 ), (y5 , x5 ), (y6 , x6 ), (y7, x7 ), (y8, x8 )(y9 , x9 )
x 1 -2 -1 0 2 3 4 -3
f (x) 2 0 3 -1 1 -2 5 1
Swapping x and y , we get the inverse fun
tion as x and y never repeats among them-
selves.
f −1 (x) = (2, 1), (0, −2), (3, −1), (−1, 0), (1, 2), (−2, 3), (5, 4), (1, −3)
Graphi
al method: The basi
prin
iple is that the graph of an inverse relation is
the ree
tion of the graph of original relation on the identity line (slope=1),y = x.
Example 3 The fun
tion f (x) = 2x + 1 has f −1 (x) = (x − 1)/2. Plots are given below
4.1. NUMERICAL METHODS 65
4 ( ) =2x +1
f x
2 f x( ) =x
1
y
−1
−2
−3
−3 −2 −1 0 1 2 3 4 5
x
Often it is ne
essary to re-
stri
t the domain on
ertain fun
tions to guarantee that the inverse relation is also a
fun
tion.
Example 4 For example if y = ax2 is the fun
tion, then it is one-to-one only for
x > 0.
1.0
0.8
0.4 ( ) =x
f x
0.2 f x ( ) = x2
0.0
0.0 0.2 0.4 0.6 0.8 1.0
x
1
1 Note that all graphs will not produ
e an inverse relation whi
h is also a fun
tion.
66 CHAPTER 4. NUMERICAL ANALYSIS
Real world numeri
al data is usually di
ult to analyse. Any fun
tion whi
h would
ee
tively
orrelate the data would be di
ult to obtain and highly unwieldy. To this
end, the idea of the
ubi
spline was developed. Using this pro
ess, a series of unique
ubi
polynomials are tted between ea
h of the data points, with the stipulation that
the
urve obtained be
ontinuous and appear smooth. These
ubi
splines
an then be
used to determine rates of
hange and
umulative
hange over an interval.
y0 yn
y1
x
x0 x1 x2 xn
Theory:
Let there be (n + 1) data points (xi , yi ), i = 0, 1, 2, ...n. The essential idea is to t a
pie
ewise fun
tion of the form
p0 (x) x0 ≤ x < x1
p (x)
1 x1 ≤ x < x2
P(x) =
... ...
pn−1 (x) xn−1 ≤ x < xn
p(x) = a3 (x − xi )3 + a2 (x − xi )2 + a1 (x − xi ) + a0
1. The pie
ewise fun
tion P(x) will interpolate all data points. That is P(xi ) =
pi (xi ) = yi
4.1. NUMERICAL METHODS 67
2. P(x) will be
ontinuous on the interval (x0 , xn ). That is pi (xi ) = pi−1 (xi )
3. The rst derivative P′ (x) will be
ontinuous on the interval (x0 , xn ). that is,
p′i (xi ) = p′i−1 (xi )
4. The se
ond derivativeP”(x) will be
ontinuous on the interval (x0 , xn ). That is,
p′′i (xi ) = p′′i−1 (xi )
The se
ond derivative of a
ubi
polynomial is of degree one ( a straight line). For the
rst pair of points (x0 , y0), (x1 , y1) the following form may be
hosen.
x − x1 x − x0
p′′0 (x) = a0 + a1
x0 − x1 x1 − x0
a0 and a1 are then given by
whi
h are the values of the se
ond derivative of p0 (x) at x = x0 and x = x1 . Integrating
p′′0 (x) with respe
t to x
(x − x1 )2 (x − x0 )2
p′0 (x) = a0 + A + a1 +B
2(x0 − x1 ) 2(x1 − x0 )
where A.B are
onstants of integration. The two
onstants are dierent be
ause the
rst term is integrated with respe
t to (x − x1 ) while the se
ond term is integrated
with respe
t to (x − x0 ) Integrating again
(x − x1 )3 (x − x0 )3
p0 (x) = a0 + A(x − x1 ) + a1 + B(x − x0 )
6(x0 − x1 ) 6(x1 − x0 )
To nd A, B we use the two given points (x0 , y0 ) and (x1 , y1). Substituting x = x0
(x0 − x1 )3 (x0 − x0 )3
p0 (x0 ) = a0 + A(x0 − x1 ) + a1 + B(x0 − x0 )
6(x0 − x1 ) 6(x1 − x0 )
(x0 − x1 )3
y0 = a0 + A(x0 − x1 )
6(x0 − x1 )
y0 a0 (x0 − x1 )
A= −
x0 − x1 6
Similarly using p0 (x1 ) = y1
(x1 − x1 )3 (x1 − x0 )3
y1 = p0 (x1 ) = a0 + A(x1 − x1 ) + a1 + B(x1 − x0 )
6(x1 − x1 ) 6(x1 − x0 )
y1 a1 (x1 − x0 )
B= −
x1 − x0 6
68 CHAPTER 4. NUMERICAL ANALYSIS
a1 (x − x2 )3
y1 a1
p1 (x) = + − (x1 − x2 ) (x − x2 )
6 (x1 − x2 ) x1 − x2 6
3
a2 (x − x1 ) y2 a2
+ + − (x2 − x1 ) (x − x1 )
6 (x2 − x1 ) x2 − x1 6
To evaluate the se
ond derivatives ai = p′′i (xi ), we use the
ondition that the rst
derivative be
ontinuous at the knots. That is, p′0 (x1 ) = p′1 (x1 ).
3a0 (x − x1 )2 y0 a0
p′0 (x) = + − (x0 − x1 )
6 (x0 − x1 ) x0 − x1 6
2
3a1 (x − x0 ) y1 a1
+ + − (x1 − x0 )
6 (x1 − x0 ) x1 − x0 6
y0 a0 a1 y1 a1
p′0 (x1 ) = − (x0 − x1 ) + (x1 − x0 ) + − (x1 − x0 )
x0 − x1 6 2 x1 − x0 6
Rearranging and simplifying
y0 a0 a1 y1 a1
p′0 (x1 ) = − (x0 − x1 ) + (x1 − x0 ) + − (x1 − x0 )
x0 − x1 6 2 x1 − x0 6
y1 − y0 a0 2a1
= + (x1 − x0 ) + (x1 − x0 )
x1 − x0 6 6
Similarly
3a1 (x − x2 )2 y1 a1
p′1 (x) = + − (x1 − x2 )
6 (x1 − x2 ) x1 − x2 6
2
3a2 (x − x1 ) y2 a2
+ + − (x2 − x1 )
6 (x2 − x1 ) x2 − x1 6
At x = x1 ,
3a1 (x1 − x2 )2 y1 a1 y2 a2
p′1 (x1 ) = + − (x1 − x2 ) + − (x2 − x1 )
6 (x1 − x2 ) x1 − x2 6 x2 − x1 6
Whi
h
an be simplied as
y2 − y1 2a1 a2
p′1 (x1 ) = − (x2 − x1 ) − (x2 − x1 )
x2 − x1 6 6
4.1. NUMERICAL METHODS 69
If the x-values are equispa
ed, let xi+1 − xi = h, then the (n − 1) equations may be
written as
4 1 0 ... 0 0 0 a1 y0 − 2y1 + y2
1 4 1 ... 0 0 0 a2
y1 − 2y2 + y3
1 4 1
... 0 0 0
a3
= 6 y2 − 2y3 + y4
.. .. .. ... .. .. .. .. h
2 ....
0 0 0 ... 1 4 1 an−2 yn−3 − 2yn−2 + yn−1
0 0 0 ... 0 1 4 an−1 yn−2 − 2yn−1 + yn
The general formula for the
ubi
polynomial between xi and xi+1 is given by
ai (x − xi+1 )3
yi ai
pi (x) = + − (xi − xi+1 ) (x − xi+1 )
6 (xi − xi+1 ) xi − xi+1 6
3
ai+1 (x − xi ) yi+1 ai+1
+ + − (xi+1 − xi ) (x − xi )
6 (xi+1 − xi ) xi+1 − xi 6
Problem 4 -Suppose
(
x3 + ax2 − 4x + c, 0≤x≤2
s(x) =
−x3 + 9x2 + bx + 34, 2≤x≤4
Problem 5 Suppose
(
ax3 + x −2 ≤ x ≤ 0
s(x) =
x3 + bx, 0≤x≤2
Problem 6 Suppose
(
0 x≤2
s(x) =
(x − 2)3 2<x
Problem 7 Using
ubi
spline interpolation te
hnique, nd y(x = 0.6) from the fol-
x 0.1 0.2 0.4 0.7 1.1
lowing data.
y 0.5754 0.6796 0.8026 0.9179 1.0231
Polynomials are used in physi
s to des
ribe the traje
tory of proje
tiles. Polynomial
integrals
an be used to express energy, inertia and voltage dieren
e. in quantum
me
hani
s, orthogonal polynomials appear as energy and momentum eigenfun
tions.
The zero or root of these polynomials gives positions and instants of zero probability
for a physi
al system. They are also used for interpolation of experimental data.
Denition 3
Pn
If p(x) = i=0 ai xi is a polynomial of degree n and p(b) = 0, then b is
alled a zero or root of the polynomial p(x).
There is an important theorem that relates the fa
tors and zeros (roots) of a polynomial.
There are 5 theorems about roots of Polynomials. They are n-Zero theorem, Remainder
theorem, Fa
tor theorem, Rational Root Theorem, Irrational Root Theorem, Complex
Root Theorem, Des
artes Rule.
p(x)
Theorem 2 (The Remainder Theorem) If = q(x)and r, the remainder, then p(b)
x−b
r
4.1. NUMERICAL METHODS 71
Proof:
p(x) = q(x)(x − b) + r, p(b) = r
To verify remainder theorem: If p(x) = x3 − x2 − 17x − 16. Let us divide p(x) by
(x − 5). The quotient is q(x) = x2 + 4x + 3 and the remainder is r = −1. Now
p(5) = 53 − 52 − 17 × 5 − 16 = −1 = r . Hen
e veried.
Proof:
p(x) = q(x)(x − b), p(b) = 0
This is a spe
ial
ase of Intermediate Value Theorem. To verify Bolzano's theorem:
If p(x) = 6x3 − 20x2 − 14x + 60. (x − 2) is a zero of this fun
tion.
A rational root is one whi
h is expressible as a quotient of two integers. In the poly-
nomial p(x) = 6x3 − 13x2 + x + 2, a0 = 2, an = a3 = 6. Hen
e the possible rational
roots are f actors of a0 /f actors of a3 = f actors of 2/f actors of 6. That is
±1, ±2
= ±1, ±1/2, ±1/3, ±1/6, ±2, ±2/3
±1, ±2, ±3, ±6
The theorem states that if there is a rational root , it must be one of these. In fa
t,
the roots are (2, 1/2, −1/3) whi
h belong to this set.
72 CHAPTER 4. NUMERICAL ANALYSIS
Theorem 6 (Irrational
√ Root Theorem) If p(x)√
is a polynomial with rational
oef-
ients and a+
√ b where a and b are rational and b is irrational is a root, then the
onjugate a − b is also a root.
√
For example, if p(x) = 2x3 − x2 − 9x − 4, its roots are x0 = 1/2, x± = (1 ± 17)/2.
Irrational roots o
ur in pairs.
Theorem 7 (Complex Root Theorem) If p(x) is a polynomial fun
tion with real
oe
ients and a + ib is a root, then a − ib must also be a root of p(x).
This theorem states that if the Coe
ients are real, all Complex Roots o
ur in
√ Conju-
gate Pairs. For example, the roots of p(x) = 3x +7x +11x+3 are x± = −1±i 2, x0 =
3 2
1/3
An obvious
orollary is for an odd-degree polynomial there exist at least one real root.
A method of determining the maximum number of positive and negative real roots
of a polynomial is given by Des
artes Rule.
For positive roots, start with the sign of the
oe
ient of the lowest (or highest) power
of x. Count the number of sign
hanges n as you pro
eed from the lowest to the
highest power (ignoring powers whi
h do not appear). Then n is the maximum number
of positive roots. Consider p(x) = x7 + x6 − x4 − x3 − x2 + x − 1. Sin
e there
are three sign
hanges, there are a maximum of three possible real positive roots.
A
tually, there is only one real positive root x = 1.1147 and three pairs of
omplex
roots −1.2 ± 0.6i, −0.3 ± i, 0.4 ± 0.5i for this polynomial.
Consider a polynomials of degree n > 2. Any one root b1 is found by any one of the
methods - bise
tion, Newton-Raphson, se
ant, Laguerre's et
. The polynomial
an
be written as a produ
t p(x) = (x − b1 )q1 (x) where q1 (x) is a redu
ed or deated
polynomial of degree n − 1. Also the roots of q1 are exa
tly the remaining roots of p.
Any one root of q1 is then determined as b2 . Deating q1 , q1 (x) = (x − b2 )q2 (x). The
same pro
edure may be repeated till the degree of qi is 2. Then quadrati
formula gives
the last two roots. This method of su
essive deation has the following advantages.
The modulus is taken sin
e logarithm of negative real numbers and
omplex numbers
are not dened. Dierentiating with respe
t to x
d ln |p(x)| 1 1 1
=+ + ..... +
dx (x − b1 ) (x − b2 ) (x − bn )
74 CHAPTER 4. NUMERICAL ANALYSIS
n
p′ (x) X 1
= = c(say)
p(x) i=1
(x − bi )
Dierentiating again
d2 ln |p(x)| 1 1 1
2
=− 2
− 2
..... −
dx (x − b1 ) (x − b2 ) (x − bn )2
′ 2 n
p′′ (x)p(x) − p′ (x)p′ (x) p′′ (x) p (x) X 1
= − =−
p(x).p(x) p(x) p(x) i=1
(x − bi )2
2 n
p′ (x) p′′ (x) X
1
− = = d(say)
p(x) p(x) i=1
(x − bi )2
Let xj − bj = ej where xj is the j th trial root and bj , the a
tual root. To nd ej ,
we assume that all other roots bi are equidistant from xj . Let xj − bi = s, i =
1, 2, .., n and i 6= j . Then
1 1 1 1 1 n−1
c = + + ..... + + .... + = +
s s ej s ej s
Similarly
1 n−1
d= 2
+
ej s2
Eliminating s and solving for ej
n
ej = p
c± (n − 1)(n d − c2 )
large. If
pc < 0, denominator is c − (n − 1)(n d − c ). If c > 0, the denominator must
2
Example-1 : To nd the roots of the polynomial p(x) = 6x4 + 23x3 + 37x2 + 28x + 6
we nd that all
oe
ients are real and positive and rational. Hen
e
omplex and
irrational roots o
ur in pairs. No
hange of sign means no real positive root. p′ (x) =
24x3 + 69x2 + 74x + 28 and p′′ (x) = 72x2 + 138x + 74. Let us assume that xj = −1.0
4.1. NUMERICAL METHODS 75
10
4
p(x)
0 b1 b2
−2
−4
−2.0 −1.5 −1.0 −0.5 0.0
x
x4 + 1x3 + 6x2 + 4x + 16
q(x) = = x2 − x + 4
x2 + 2x + 4
The roots of this√quadrati
equation are given by x± = 0.5 ± 1.9365j . Hen
e the set of
roots are (−1 ± 3j, 0.5 ± 1.9365j)
Problem 8 Gas tank that is 10 meters in length (end to end)
onsists of a right-
ylinder and is
apped at either end by a hemisphere. What is the radius of the tank if
the volume is 50
ubi
meters?
x3 + x − 10
q(x) = = x2 + 2x + 5
x−2
4.1. NUMERICAL METHODS 77
Example-4 : To nd the roots of a
ubi
polynomial p(x) = 6x3 − 11x2 − 14x + 24,
we observe that there are 2 sign
hanges so that there may be 2 positive roots. As
before we start with xj = 0 in Legurre's pro
edure. Su
essive iterations give xj =
0.9101, 1.3001, 1.3333(= 4/3) Hen
e x − 4/3 or (3x − 4) is a fa
tor.
√
No. polynomial p(x) Answer(j = −1)
1 x4 − 10x3 + 35x2 − 50x + 24 1, 2, 3, 4
2 x4 − 2x3 + 2x − 1 1, −2, −3, 4
3 x4 − 3x3 − 3x2 + 11x − 6 2, −1/3, 3/2, 2
4 x4 − 4x3 + 6x2 − 4x + 1 1, 3, (2 ± 1j)
5 x4 + 4x3 + 6x2 + 4x + 5 2 ± j, 0 ± j
6 x3 − 3x2 + 3x − 1 (2 ± 3j), 4
7 x3 − 6x2 + 11x − 6 2, 3, 4
8 x3 − 4x2 + 5x − 2 (1 ± 5j), 3
9 x3 − 8x2 + 20x − 16 3, 3, 0.5
For example,
onsider tossing a pair of
oins. The number of heads n showing when
the
oins land is a random variable. It
an be assigned the number 0 to the out
ome
[Tail, Tail℄. That is n(T, T ) = 0. Similarly n(T, H) = n(H, T ) = 1 and n(H, H) = 2.
Denition 5 (Expe
tation or Expe
ted Value) The expe
ted value of a random
variable is the long-term limiting average of its values in independent repeated events.
The expe
ted value of the random variable X is denoted E[X℄. For example, while
tossing a
oin, the fra
tion of times the
oin lands with head up is half when the
number of tosses are very large. It is expressed as E[n(H)] = 0.5. This idea
an be
expressed mathemati
ally as follows. Let a random variable X takes a values xi with
probability pi . If the sum of produ
ts
onverges absolutely to some value Y , that is,
n
X
lim pi .xi = Y
n→∞
i=1
, then Y is the expe
tation of X . For a
ontinuous random variable X , the expe
tation
may be dened as Z
E[X] = xP (x)dx
Taking the expe
ted value is a linear operation: if X and Y are two random
variables,E[X + Y ] = E[X] + E[Y ], and for any
onstant a, E[aX] = aE[X]
Theorem 9 (Law of large numbers) As the number of trials of a random pro
ess
in
reases, the per
entage dieren
e between the expe
ted values and a
tual values (mean
measured values) of all random variables goes to zero.
Simple integration
b N
b−aX
Z
f (x)dx = lim f (xi )
a N →∞ N
i=0
N
1 X
lim f (xi ) = lim hf (xi )i = E[f ]
N →∞ N N →∞
i=0
The error e in the above
al
ulation is the dieren
e between the expe
ted value and the
mean value whi
h is given by their standard deviation. For a k -dimensional integral,
it is given by r
hf 2 i − hf i2
e = ±τ
N
where τ is k -dimensional volume and hf 2 i = N i=0 f (xi ). It is only a rough estimate
2
P
of the error.
Numeri
al pro
edure: In order to integrate a fun
tion over a
ompli
ated domain
D , Monte Carlo integration uses random points over some simple domain D ′ , whi
h
en
loses D . Ea
h random number generated is then
he
ked to see whether it is within
80 CHAPTER 4. NUMERICAL ANALYSIS
D . Out of the n random numbers, if m are within D , then the ratio (m/n) gives the
ratio of n-dimensional volumes D/D ′ . For example, to
al
ulate the area D of one
quadrant of a
ir
le of radius r , we en
lose it within a square (D ′ ) of side r . Pairs
of random numbers (xi , yi ) in the interval (0, r) are generated and
he
ked to see if
x2 + y 2 ≤ r 2 so that it is within D . The ratio m/n of the number of random pairs to
the total number of pairs gives the ratio of their areas D/D ′ . Then
D = D ′ (m/n)
1.0
0.8
0.6
0.4
0.2
0.0
0.0 0.2 0.4 0.6 0.8 1.0
.
R 2π dθ √
For example, the integral 0 whi
h is 2π/ 3 = 3.62759872847, gives the
2 + cos θ
following values.
No.of random points in (0, 2π) Value of integral
10000 3.63293517
20000 3.63805025
30000 3.63569129
40000 3.63152102
50000 3.62770939
Importan
e sampling: The term importan
e sampling refers to the pro
ess of
las-
sifying values of the input random variables in a simulation a
ording to the impa
t on
the quantity being estimated. If the large impa
t values (important values) are empha-
sized by sampling more frequently, then the varian
e of the estimated quantity
an be
redu
ed. Hen
e, the basi
methodology in importan
e sampling is to
hoose a distri-
bution whi
h gives more weight to the important values. In a simulation, outputs are
again weighted to
orre
t for the use of the biased distribution. This ensures that the
new importan
e sampling is unbiased. Thus the fundamental problem in importan
e
sampling is to determine the distribution that is properly biased. Su
h a distribution
saves large amounts of
omputing time.
Sampled data refers to a subset of a large data system that is dis
rete or
ontinuous
and whi
h has all the
hara
teristi
s of the
omplete data system. The size of the
sample required for this purpose is given by sampling theorem.
Here band-limited signal refers to a signal with a zero power for frequen
ies ν > νm .
A signal sampled at f = 2νm is said to be Nyquist sampled, and fc is
alled the
Nyquist
riti
al frequen
y. No information is lost if a signal is sampled at fc , and no
additional information is gained by sampling faster than this rate. For example, to
sample a sine wave of frequen
y ν , the minimum sampling rate is fc = 2ν . That is the
time interval ∆ between samples and period of sine wave T are related as Delta = T /2.
Hen
e a
onvenient
hoi
e is to sample at positive and negative peak of the wave. If h(t)
ontains frequen
ies f outside of the range (−f c, f c) where fc is the Nyquist frequen
y,
then the power
ontent of these frequen
ies is moved into that range −fc < f < fc so
that power spe
trum is modied. This phenomenon is
alled aliasing . Any frequen
y
omponent outside of the range (−f c, f c) is translated into that range as a result of
dis
rete sampling.
Consider a fun
tion h(t) of a
ontinuous variable t transformed into a fun
tion H of
another independent variable ω having range (−∞, ∞) by the equation
Z ∞
H(ω) = h(t)eiωt dt
−∞
The integration in these transforms
an be repla
ed with a summation over the fun
tion
values h(t)
orresponding to properly sampled values of t. Consider N
onse
utive
sampled values at
onstant separation ∆. Let
If the fun
tion h(t) is
ontinuous and not periodi
, then we assume that the sampled
points are su
h that h(t) is similar in stru
ture at all times t. Even though all frequen-
ies in the Nyquist frequen
y range (−fc , fc ) are possible, we
an get Fourier transforms
H(fk ) only for N -frequen
ies as there are only N -input samples. Consider N values
n
fn = , n = [N/2, (N/2) − 1, (N/2) − 2, ...(−N/2) + 1, −N/2]
N∆
The extreme values of n, that is ±N/2 exa
tly
orrespond to the lower and upper limits
±fc . If ωn = 2πfn , then the dis
rete Fourier transform is given by
Z ∞ N −!
X N −!
X
iωn t (iωn tk )
H(ωn ) = h(t)e dt ≈ hk e ∆=∆ hk e(iωn k∆)
−∞ k=0 k=0
4.1. NUMERICAL METHODS 83
The quantity
N −!
X 2πikn
hk exp = Hn
k=0
N
where Hn is
alled the dis
rete Fourier transform of the N points hk .
H(fn ) ≈ Hn ∆
Program: The following fun
tion will
al
ulate the dis
rete Fourier transform of list
of values x.
y[p℄ = s
return y
print dft([1,3,5,3,1,-1,-3℄)
Output
[(9+0j), (-3.49+11.41j), (-0.11+1.681j), (2.60-0.14j),
(2.60+0.14j), (-0.11-1.68j), (-3.49-11.41j)℄
Thus the
al
ulation of dis
rete Fourier transform of N -sampled points requires N ×
N = N 2
omputations. There is an algorithm to redu
e the number of
omputations
N log2 N
alled Fast Fourier Transform.
This algorithm was rst
on
eived by Gauss in the 18th
entuary. With the advent of
modern
omputers, Tukey and Cooley developed an algorithm to implement it on a
digital
omputer. There are other algorithms similar to this one developed re
ently.
The basi
prin
iple is the divide and
onquer strategy just like any other large data
systems. The dis
rete Fourier transform of n-sampled points requires N × N = N 2
omputations. If the data set is divided into two equal parts, ea
h part requires N 2 /4
omputations for its Fourier transform. Hen
e total number of
omputations is only
N 2 /2 = N 2 /21 whi
h shows a redu
tion by N 2 /2. If ea
h half is still divided, the
number of
omputations gets redu
ed to 4 × (N/4)2 = N 2 /4 = N 2 /22 In general if
the N = 2p -points are divided into M = 2q equal parts, the number of
omputations
be
omes N 2 /2M = 22p−q .
Pro
edure: There are dierent algorithms for FFT. One of the simplest is the Sande-
Tukey algorithm. It is given below.
Let N = 2p an integer power of 2. If the length of the data set is not a power of two,
zeros may be added as data elements up to the next power of two. If fn are n-data
points separated by N equal intervals, then its dis
rete Fourier transform (DFT) is
given by
N
X −1
Fk = fn W nk , k = 0, 1, 2, 3..N − 1
n=0
where W = e2πi/N . Let us divide the entire data into two sets-odd and even indi
es-
4.1. NUMERICAL METHODS 85
(N/2)−1 (N/2)−1
X X
2nk
Fk = f2n W + f2n+1 W (2n+1)k
n=0 n=0
(N/2)−1
X
W 2nk f2n + f2n+1 W k
=
n=0
(e) (o)
= Fk + W k Fk
(e) (o)
where Fk = N/2−1 W 2nk f2n and Fk = N/2−1 W 2nk f2n+1 , supers
ript 'o' and 'e'
P P
n=0 n=0
stands for odd and even number4ed data. The
rux of the solution is to
onsider these
odd and even sets of N/2 numbers as transforms of sequen
es of length N/2. This is
alled Danielson-Lan
zos Lemma. It is found that this Lemma
an be used re
ursively.
(e) (o)
Having redu
ed the problem of
omputing Fk to that of
omputing Fk and Fk , the
(e)
same redu
tion of Fk to the problem of
omputing the transform of its N/4 even-
(ee)
numbered input data (even k in f2k ) as Fk and N/4 odd-numbered data (odd k in
(eo) (o) (oe) (oo)
f2k ) Fk . Similarly division of Fk
an also be done into Fk and Fk . In other
words, one
an dene dis
rete Fourier transforms of the points whi
h are respe
tively
even-even, even-odd, odd-even and odd-odd on the su
essive subdivisions of the data.
Sin
e N is a power of 2, it is evident that one
an
ontinue applying the Danielson-
Lan
zos Lemma until we have subdivided the data all the way down to transforms of
length 1. The Fourier transform of length one is just the identity operation that
opies
its one input number into its one output slot! In other words, for every pattern of
log2 N there is a one-point transform that is just one of the input numbers fn for some
n.
Shooting method is employed to solve ordinary se
ond order dierential equations with
a pair of boundary
onditions . It is a two-point boundary value problem. The bound-
ary
onditions at the starting point do not determine a unique solution to start with.
Starting boundary
onditions is almost
ertain not to satisfy the boundary
onditions
at the other boundary point. In general, iteration is required to
orrelate boundary
onditions into a single global solution of the dierential equation. Dierential equa-
tions are to be integrated over the interval of interest several times. Only for linear
dierential equations, the number of iterations
an be predi
ted. Consider the general
form of a se
ond order linear dierential equation for the fun
tion y(x)
with boundary
ondition y(a) = α, y(b) = β . Suppose u(x) is a fun
tion whi
h satises
the above equation with initial
onditions u(a) = α, u′ (a) = 0
β − u(b)
u(b) + cv(b) = β, c =
v(b)
Pro
edure: Any se
ond order linear dierential equation
an be split into two
ou-
pled rst order equations and solved by Runge-Kutta method if two initial
onditions
are known. In linear shooting method, the following pro
edure is followed.
1. First solve
u′(x) = s(x), u(a) = α
s′ (x) = p(x)s(x) + q(x)u(x) + r(x), s(a) = 0
2. Then solve
v ′ (x) = t(x), v(a) = 0
t′ (x) = p(x)t(x) + q(x)v(x), t(a) = 1
β − u(b)
y(x) = u(x) + v(x)
v(b)
4.1. NUMERICAL METHODS 87
It is an approa
h dierent from shooting method. The dierential equations are re-
pla
ed by nite-dieren
e equations between a set of points in the range of integration.
The
onversion of a dierential operator to a dieren
e operator is done as follows. Let
y0 , y1 , y2 be three points
orresponding to the x-values x0 , x0 + δx, x0 + 2δx respe
tively
′ dy y1 − y0 y1 − y0
y (x0 ) = ≈ =
dx x=0 x0 + δx − x0 δx
′
y1′ − y0′
′′ dy y2 − y1 y1 − y0 1 y2 − 2y1 + y0
y (x0 ) = ≈ ≈ − =
dx x=0 δx δx δx δx (δx)2
Pro
edure: The method of solution involves the following steps. Let y(x) be the
unknown fun
tion
2. A trial solution is assumed whi
h
onsists of values for the dependent variables
at ea
h mesh point. It may not satisfy the desired nite-dieren
e equation, nor
the required boundary
onditions.
5. This iterative pro
ess is
ontinued till the solution is in
lose agreement with
the true solution. This is indi
ated by the agreement with dieren
e equation
and boundary
ondition. Also further iteration will not
hange the solution
signi
antly.
• If the boundary onditions are subtle, or involve ompli ated algebrai relations.
• If a good initial guess is possible, relaxation methods are very e
ient. Often
it may be ne
essary to solve a problem many times, ea
h time using a slightly
dierent value of some parameter like an eigenvalue. In that
ase, the previous
solution is usually a good initial guess when the parameter is
hanged.
Chapter 5
Simulations
Simulation in physi
s refers to the imitation of the behaviour of physi
al systems with
time (temporal evolution). Time evolution of a system follow deterministi
laws. These
laws are invariably dierential equations. If the dierential equations are non-linear
or they are sets of
oupled equations, analyti
solutions are either too di
ult or
impossible without heavy approximations. Numeri
al solutions are the only alternative
in those
ases. To redu
e the errors in the results, often one has to use a large number
of time steps. A
omputer be
omes an absolute ne
essity in su
h
ases. By
hanging
variables in the simulation, the behaviour of the system under dierent
ir
umstan
es
an be studied virtually. It thus leads to the
on
ept of a theoreti
al lab.
The number of steps involved depends generally on the
omplexity of the phenomena
to be simulated. But the following 7 steps are mandatory.
d2 x
ax = = k.x/r 3
dt2
d2 y
ay = 2 = k.y/r 3
dt
5. Choose a suitable method of solution of the equation. For ordinary dierential
equations any of these methods- Runge-Kutta, predi
tor-
orre
tor, Monte-Carlo,
Euler et
.-may be used. In Euler method.
vx = vx0 + ax dt
vy = vy0 + ay dt
x = x0 + vx dt
y = y0 + vy dt
6. Solve the equation for dierent values of the variable starting from initial values
and in
rementing in steps of proper size.
Cal
ulate [x(t + n dt), y(t + n dt)] from [x{t + (n − 1)dt}, y{t + (n − 1)dt}].
7. Either print the output as a table of values or plot the output as a graph.
Prin iple
d2 x
+ ω 2x = 0
dt2
This
an be split into 3 equations using a
eleration a, velo
ity v and displa
ement x
as follows.
a = −ω 2 x, δv = a δt, δx = v δt
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 91
vi = vi−1 + a δt
xi = xi−1 + vi δt
The x − t graph and x − v graph (Phase urve) are drawn for the os illator.
Program
ylabel("a
eleration")
grid(True)
plot(t,a)
show()
3 3
2 2
displacement
1 1
velocity
0 0
−1 −1
−2 −2
−3 −3
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
time time
3 3
2 2
acceleration
1 1
velocity
0 0
−1 −1
−2 −2
−3 −3
−3 −2 −1 0 1 2 3 0 1 2 3 4 5 6 7
displacement time
A for
e eld having a potential fun
tion V (r, θ, φ) = V (r) is
alled a
entral eld. As
it depends only on r it has spheri
al symmetry and
onsequently angular momentum
is
onserved. Gravitational eld and Coulomb eld are examples of
entral elds. The
general form of the potential is V (r) = kr n where k is a
onstant and n a real number.
Rutherford s
attering is an example of motion in a repulsive
entral eld.
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 93
B(xn , yn )
.
......
......
......
......
.
..
.......
.
.
.......
.......
.......
.......
.......
..
..
.......
.
....
.......
......
.......
........
.......
..
..
........
.
....
.......
........
.........
.......
........
..
..
..
.........
.
.....
.........
.........
.........
..........
..........
..
..
..
..
...........
.
.......
...........
............
............
.............
..............
...............
.
..................
........................
................................................................................................................................................
.
..
..
..
..
..
..
..
θ
A(x1 , y1 ) C
① b
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̂
4πǫ0 r 2
2ze2 x
ax = (1)
4mπǫ0 r 3
2ze2 y
ay =
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
2
= 2 (2)
dt (x + y 2 )3/2
d2 y cy
2
= 2
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) =
yn − y0
94 CHAPTER 5. SIMULATIONS
4.0 4.5
3.5 4.0
3.0 3.5
cot(theta/2)
2.5 3.0
y
2.0 2.5
1.5 2.0
1.0 1.5
0.5 1.0
0.0 0.5
−6 −4 −2 0 2 4 6 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
x impact parameter b
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 3 and 5.1.2
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
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
subplot(1,2,1)
xlabel('x')
ylabel('y')
title("Path of alpha parti
le")
plot(x,y)
otthetaby2[j℄=(x[i℄-x[0℄)/(y[i℄-y[0℄)
subplot(1,2,2)
xlabel('impa
t parameter b')
ylabel('
ot(theta/2)')
title("Relation between b and theta")
grid(True)
plot(b,
otthetaby2)
show()
Prin iple
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 π .
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
ative
ongruential re
ursive method developed by D.Lehmer. The ith and (i + 1)th random
numbers are related as
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.
(0,1)
..................... (1,1)
................
............
...........
..........
.........
........
.......
......
.......
......
......
.....
.....
.....
.....
.....
....
....
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
..
.. (1,0)
(0,0)
Algorithm
1: Read N ,the
ount of random numbers to be generated
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
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 97
Program
Prin iple
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
rete 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.
1. The roots of logisti
equation are obtained by setting f (x) = 0. They are x=0
and x=1.
2.
df (x)
= c(1 − 2x)
dx
3. After some iterations of the map , it often
onverges to some xed value
alled
an 'attra
tor'. Any further iteration of will yield the same value. If x∗n is su
h a
value,
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 bifur
ation of the attra
tor at c = 3 is
alled pit
hfork bifur
ation due to its
shape.
|f (f (xn ))| ≤ 1
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 99
√
This requires c ≥ 1 + 6 = 3.449489743. Then ea
h bran
h of xed points bifur
ates
into two separate bran
hes. The points on these bran
hes will be of period 4.
If c is further in
reased, further bran
hing o
urs. Fixed points of period p give rise
to 2p bran
hes. It is found that for c = 3.5699....., an innite number of bifur
ations
o
ur. In logisti
map, xed points never repeat. The band of xed points forms a
ontinuum. Complete
haos begins from this point. Thus bifur
ation is the route to
haos for logisti
equation.
Logistic Map
1.0
0.8
0.6
Population
0.4
0.2
Program
C L
v(t)
Prin iple:
If a voltage v(t) is given to a series LCR- ir uit, Kir ho's voltage law gives
di q
L + Ri + = V (t)
dt C
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 101
d2 q dq q
L + R + − V (t) = 0
dt2 dt C
This se
ond order dierential equation
an be split into two rst order
oupled equa-
tions and solved simultaneously.
Let
dy dz
= f (x, y, z), = g(x, y, z)
dx dx
be two
oupled equations with initial
onditions y(x0) = y0, z(x0) = z0. Then the
values y(x + δx), z(x + δx) are given by a 4-step determination of slopes at x0, x0 +
δx/2, x0+δx/2, x0+δx su
essively as follows. let δx = h whi
h is the usual
onvention.
k1=h f(x0,y0,z0)
m1=h g(x0,y0,z0)
k2=h f(x0+h/2,y0+k1/2,z0+m1/2)
m2=h g(x0+h/2,y0+k1/2,z0+m1/2)
k3=h f(x0+h/2,y0+k2/2,z0+m2/2)
m3=h g(x0+h/2,y0+k2/2,z0+m2/2)
k4=h f(x0+h,y0+k3,z0+m3)
m4=h g(x0+h,y0+k3,z0+m3)
y(x0+h)=y0+(k1+2 k2+2 k3+k4)/6
z(x0+h)=z0+(m1+2 m2+2 m3+m4)/6
Using the pair (y(x0 + h), z(x0 + h) the values at x0 + 2h (y(x0 + 2h), z(x0 + 2h) are
found using the above formula. The pro
ess is repeated till we get the value of (y, z)
at the desired x.
Program:
def f(x,y,z):return z
def g(x,y,z):return (-0.2*z-y+sin(4*x))#L=1H,C=1F, omega=4/s,R=0.2ohm.
s=rk4solution(f,g,0.,0.,0.,0.05,1000)
figure(1)
subplot(1,2,1)
xlabel('time')
ylabel('
harge')
title('Charge variation')
grid(True)
plot(s[0℄,s[1℄)
subplot(1,2,2)
xlabel('time')
ylabel('Current')
title('Current variation')
grid(True)
plot(s[0℄,s[2℄)
figure(2)
xlabel('Charge')
ylabel('Current')
title('Current-Charge plot')
grid(True)
plot(s[1℄,s[2℄)
show()
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 103
0.3
Charge variation Current variation
0.4
0.2
0.2
0.1
Current
charge
0.0 0.0
−0.1
−0.2
−0.2
−0.4
−0.3
0 10 20 30 40 50 0 10 20 30 40 50
time time
The graphs show some initial distortions but later starts os
illating with the im-
pressed frequen
y ω . It
an be explained if we look at the analyti
solution of the
104 CHAPTER 5. SIMULATIONS
dierential equation
d2 q dq q
L 2 + R + − V0 sin (ωt)(t) = 0
dt dt C
d2 q dq
2
+ 2γ + ω02 q − v0 sin (ωt)(t) = 0
t dt
where 2γ = R/L, ω02 = 1/LC, v0 = V (0)/L
where A is real and positive amplitude, φ, ψ are additional phases ω ′ = ω02 − γ 2 and
p
v0
B=p
(ω02 − ω 2)2 + 4γ 2 ω 2
The rst term of the solution represents damped os
illations while the se
ond term gives
the for
ed os
illations. They interfere to give some distorted waveforms. Gradually the
amplitude of damped os
illation redu
es to zero and the LCR-
ir
uit starts os
illating
with impressed frequen
y.
Standing waves are produ
ed when a travelling wave gets ree
ted and superimpose
with the original wave.
Prin iple
Let y1 = f (x − vt) be the forward wave and y2 = f (x + vt) be the ree
ted wave. Then
y = y1 + y2 will be the
omposite wave. If it is a harmoni
wave of spatial frequen
y
k = 2π/λ and angular frequen
y ω = 2πν , it
an be represented as y1 = A sin (kx − ωt)
and y2 = A sin (kx + ωt). Hen
e superposed wave is given by
It
an be seen that the superposed pattern
onsists of points of zero amplitude
alled
nodes . Energy is not transmitted through nodes. Hen
e the name stationary waves.
5.1. A COMPUTATIONAL APPROACH TO PHYSICS 105
1.5
1.0
0.5
0.0
x
−0.5
−1.0
−1.5
−2.0
0 2 4 6 8 10
displacement y
Program
Prin iple
∆N(t)
= −λ∆t, ∆N(t) = −λ∆tN(t)
N(t)
Algorithm
1: Read N ,D ,(initial number of parent and daughter atoms), maximum no of time
intervals m and de
ay
onstant λ
2: T ←0
3: while N > 0 and T < m do
4: NU ← N
5: for i = 1 to NU do
6: x ← rand()
7: if 0 < x ≤ lambda then
8: N ←N −1
9: end if
10: end for
11: T ←T +1
12: end while
13: End
Program:
NU+=[N℄
T+=1
T=arange(T+1)
plot(T,NU)
plot(T,Y)
Y=NU[0℄*exp(-Lambda*T)
legend(['Simulated','Exponential'℄)
xlabel('time')
ylabel('No.of unde
ayed atoms')
title('Radioa
tive de
ay')
grid(True)
It
an be seen that as N in
reases, the de
ay graph
oin
ides with the exponential
urve.
dN
Hen
e the dierential equation = −λdt is only a large-number approximation of
N
∆N
the dieren
e equation = −λ∆t
N
Radioactive decay
100
Simulated
Exponential
80
No.of undecayed atoms
60
40
20
0
0 2 4 6 8 10
time
Index
108
INDEX 109
genfromtxt, 35 multidimensional, 29
grid(), 50 multipli
ative
ongruential re
ursive method,
96
Hailstorm number, 21 mutable, 5
harmoni
wave, 104
hermitian matrix, 46 n-Zero theorem, 70
homogeneous, 29 ndarray, 29
Newton-Raphson method, 24, 25
if, 14 node, 104
image, 61 non-singular, 45
immutable, 5, 10, 12 norm, 45
importan
e sampling, 81 numeri
, 2
imshow, 54 Numpy, 49
imshow(), 1 numpy, 15
index, 7, 39 Nyquist
riti
al frequen
y, 82
inner produ
t, 39 Nyquist sampled, 82
input, 1 Nyquist-Shannon Sampling Theorem, 81
insert, 7
interpolate, 66 ogrid[℄, 51
interse
tion, 10 one-to-one, 62
inv, 45 one-to-one mapping, 61
inverse fun
tion, 61 onto mapping, 61
invertible matri
es, 45 open, 16
irrational roots, 74 operand, 3
operator, 3
key, 12 orthogonality, 22
os, 15
Laguerre's Method, 73 outer, 40
law of large numbers, 78 outer produ
t, 40
legend(), 50
Legendre Fun
tion, 57 palindrome, 23
Legurre's pro
edure, 76 parametri
plot, 53
linalg, 45 Pas
al's triangle, 20
linear algebra, 45 Permutation, 19
linear equation, 45 pi
kle, 16
list, 2, 5 Pie
harts, 53
load, 16 pinv, 45
logisti
map, 97 plot(), 49
loglog plot, 51 Polar
oordinate, 52
polar plot, 51
magi
numbers, 96 pop, 7
math, 15 preimage, 61
Matplotlib, 49 prime number, 23
module, 15 pseudo-random numbers, 95
Monte Carlo, 77, 95 pseudoinverse, 45
110 INDEX
pylab, 15 String, 4, 5
string, 2
quadrati
equation, 22 swapping method, 64
quadrati
formula, 77 symmetri
dieren
e, 10
random, 15 text(), 50
random variable, 78 the horizontal line test, 62
rational number, 52 title(), 50
ravel, 33 transpose, 33
raw_input, 1 triangular sequen
e, 20
read, 16 tuple, 5, 12
relaxation method, 87 tuples, 2
Remainder theorem, 70
remove, 7 unary operation, 42
reshape, 33 union, 10
reshape fun
tion, 34 unit matrix, 30
resize, 33
reverse, 8 varian
e, 80
rhodonea, 52 write, 16
Robert May, 97
rose
urve, 52 xlabel(), 50
sampling, 80 ylabel(), 50
sampling theorem, 81
Sande-Tukey algorithm, 84
saveg(), 1
savetxt, 35
s
atter plot, 51
semilogx, 51
semilogy, 51
shooting method, 85
show(), 1, 49
simple harmoni
os
illator, 90
simulation, 81
sinusoid, 52
skiprows, 35
sli
e, 39
solve, 45
sort, 8
sorted, 8
spatial frequen
y, 104
square matrix, 46
square root, 24
standard deviation, 79
standing waves, 104