0% found this document useful (0 votes)
90 views133 pages

Computational Physics 5 TH Sem

Computational Physics
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)
90 views133 pages

Computational Physics 5 TH Sem

Computational Physics
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/ 133

PHY5B06

COMPUTATIONAL PHYSICS

SULAIMAN .MK
Assistant Professor of Physics
Govt. College Malappuram
Module-1:
Introduction to
Python Programming
16 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


2
Malappuram
Language
• The method of human communication, either spoken or written,
consisting of the use of words in a structured and conventional way
(Oxford dictionary)
• Language, a system of conventional spoken, manual, or written
symbols by means of which human beings, as members of a social group
and participants in its culture, express themselves. The functions of
language include communication, the expression of identity, play,
imaginative expression, and emotional release (Encyclopaedia Britannica)

Sulaiman M.K, Assistant Professor of Physics, Govt. College


3
Malappuram
Programming Language
• A programming language is a vocabulary and set of grammatical rules
for instructing a computer or computing device to perform specific tasks.
eg:- BASIC, C, C++, COBOL, Java, FORTRAN, Ada, Pascal and
Python.
• Each programming language has a unique set of keywords (words that it
understands) and a special syntax for organizing program instructions.

Sulaiman M.K, Assistant Professor of Physics, Govt. College


4
Malappuram
High Level Language
• A high-level language (HLL) is a programming language that enables a
programmer to write programs that are more or less independent of a
particular type of computer. Such languages are considered high-level
because they are closer to human languages and further from machine
languages. E.g. Fortran, C, Pascal, Python
• It is the set of well defined notations, which is capable of expressing the
algorithms
• In contrast, assembly languages are considered low-level because they
are very close to machine languages
• FORTRAN in 1957 is the first high level language

Sulaiman M.K, Assistant Professor of Physics, Govt. College


5
Malappuram
Features of a High Level Language
• Machine independent
• Must use simple syntax familiar to some human language like English
• Ability to represent different data types like characters, integers etc.
• Arithmetic and logical operators that act on supported data types
• Control flow structures for decision making, looping, branching etc.
• Must have a set of syntax rules that specify the combination of words
and symbols
• Must have a set of semantic rules that assigns a single, precise and
unambiguous meaning to each syntactically correct statement
Sulaiman M.K, Assistant Professor of Physics, Govt. College
6
Malappuram
Compilers and Interpreters
• A compiler is a computer program that translates source code into
object code
• Compiler takes as the input specification for an executable program and
produces as output the specification for another, equivalent executable
program
• An interpreter translates some form of source code into a target
representation that it can immediately execute and evaluate

Sulaiman M.K, Assistant Professor of Physics, Govt. College


7
Malappuram
Comparison of Interpreter and Compiler
COMPILER INTERPRETER
Takes Entire Program as Input Takes Single Instruction as Input
Intermediate Object Code is Generated No Intermediate Object Code is Generated
Conditional Control Statements Executes Conditional Control Statements Executes
Faster Slower
Memory Requirement is More (Since Memory Requirement is Less
Object Code is Generated)
Program need not be Compiled Every Every Time High Level Program is
Time Converted into Lower Level Programs

Errors are Displayed after Entire Program Errors are Displayed for Every
is checked Instruction Interpreted
Eg: C, Fortran Eg:
Sulaiman M.K, Assistant Professor of
Malappuram
Physics,Basic,
Govt. CollegePython
8
Module-1:
Introduction to
Python Programming
(Lecture-3)
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Input Functions
• 1) input( ) - General format: input(‘prompt’)
It is to read all data types as string
>>> a=input('enter your register number’)
enter your register number 25
>>> a
‘25’
• 2)raw_input( ) – General format: raw_input(‘prompt’)
It is to read strings or characters. This not defined in python 3

Note:- To read any data as itself using input ( ) function, use eaval ( )
Sulaiman M.K, Assistant Professor of Physics, Govt. College
2
Malappuram
Output Functions
• Output of a program may number, text or graphics
• print ( ) statement for numbers and texts
• show( ), imshow( ),savefig( ) etc. for graphics

>>> print ('Good Morning!!')


Good Morning!!
>>> print ("Good Morning")
Good Morning

Sulaiman M.K, Assistant Professor of Physics, Govt. College


3
Malappuram
Formatted Print
• Formatted output is possible in python like C.
• General Format: %m.nx
• m is the integer showing total width
• n is the integer representing number of decimal places and
• x represents the type of data (c- single character, f- float, e-float in
scientific format, s-string, x –hexadecimal, o – octal, d or i – integer)
>>> print ('The number is:25’)
The number is:25
>>> print ('The number is:%10.5f'%(25))
The number is: 25.00000
Sulaiman M.K, Assistant Professor of Physics, Govt. College
4
Malappuram
Variables and Data types
Text Type: str
Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset


Sulaiman M.K, Assistant Professor of Physics, Govt. College
5
Malappuram
Module-1:
Introduction to
Python Programming
(Lecture-4)
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Operators
• Operators are functionality which do some thing on data known as
operands
• Python supports 7 types of operators
• 1) Arithmetic Operators 2) Comparison Operators
• 3) Assignment Operators 4) Logical Operators
• 5) Bitwise Operators 6) Membership Operators
• 7) Identity Operators

Sulaiman M.K, Assistant Professor of Physics, Govt. College


2
Malappuram
1) Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Sulaiman M.K, Assistant Professor of Physics, Govt. College
3
Malappuram
2) Comparison Operators
Operator Name Example
== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Sulaiman M.K, Assistant Professor of Physics, Govt. College
4
Malappuram
3) Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
Sulaiman M.K, Assistant Professor of Physics, Govt. College
5
Malappuram
4) Logical Operators

Operator Description Example


and Returns True if both statements are x < 5 and x < 10
true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

Sulaiman M.K, Assistant Professor of Physics, Govt. College


6
Malappuram
5) Bitwise Operators
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from
shift the left, and let the rightmost bits fall off

Sulaiman M.K, Assistant Professor of Physics, Govt. College


7
Malappuram
6) Membership Operators
Operator Description Example
in Returns True if a sequence x in y
with the specified value is
present in the object

not in Returns True if a sequence x not in y


with the specified value is
not present in the object

Sulaiman M.K, Assistant Professor of Physics, Govt. College


8
Malappuram
7) Identity Operators
Operator Description Example

is Returns true if both x is y


variables are the same
object
is not Returns true if both x is not y
variables are not the
same object

Sulaiman M.K, Assistant Professor of Physics, Govt. College


9
Malappuram
Precedence Rules of Operators
• 1. ( ) (anything in brackets is done first. Highest precedence)
• 2. ** (exponentiation is done next)
• 3. -x, +x (unary ±)
• 4. *, /, %, // (multiplication, division, remainder after division, successive
division)
• 5. +, - (addition, subtraction)
• 6. relational operators: <, >, <=, >=, !=, ==
• 7. logical not
• 8. logical and
• 9. logical or (Lowest precedence)
Sulaiman M.K, Assistant Professor of Physics, Govt. College
10
Malappuram
Module-1:
Introduction to
Python Programming

18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Strings
• String is a compound data type
• Collection of characters of same kind
• String is an immutable data type
• In single quote or double quote
• e.g. name=‘Government College’
• or name=“Government College”

Sulaiman M.K, Assistant Professor of Physics, Govt. College


2
Malappuram
• Can be indexed
>>> a1='Govt College'
>>> a1[0]
'G'
>>> a1[2]
'v'
>>> a1[-1]
'e'
>>> a1[-2]
'g’

• Can be sliced
>>> a1[1:8:2]
'otCl'
Sulaiman M.K, Assistant Professor of Physics, Govt. College
3
Malappuram
• Can be added (+ concatenation)
>>> a='govt '
>>> b= 'college'
>>> a+b
'govt college'
• Multiplied (* repetition)
>>> a*3
'govt govt govt '
• len( ) will give number of elements
>>> len(b)
7
• Membership can be checked using in, not in
>>> 'c' in b
True
Sulaiman M.K, Assistant Professor of Physics, Govt. College
4
Malappuram
Module-1:
Introduction to
Python Programming
(Lecture-6)
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Lists
• Collection of elements of any type of elements
• Elements enclosed in a square bracket and separated by commas
• Mutable data type
• A=[1,2,3,[1,2],‘Govt’, “college”]

• Can be indexed
• Can be sliced
• Can concatenate by +
• Repetition possible by *

Sulaiman M.K, Assistant Professor of Physics, Govt. College


2
Malappuram
• len(name) == will give number of elements
• Membership can be checked using in, not in
• In python 2 easy way to create a list is range( ) function
• General format: range(i,j,p) from ith to (j-1) th with p step
where i,j and p must be integer values
• In python 3, it create a separate class/data type range with similar
properties
In python 2.x
>>> range(1,11,2)
[1, 3, 5, 7, 9]
In python 3.x
>>> range(1,10)
range(1, 10)
Sulaiman M.K, Assistant Professor of Physics, Govt. College
3
Malappuram
List Methods
A method is a function that is coupled to some object to modify or
examine the content of the object
General format is object.Method ( ) for a=[1,2,3,1,5]
1) append >>> a.append(5) >>>a >>> [1,2,3,1,5,5]
2) count >>>a.count(2) >>> 1
3) extend >>>a.extend([5,6]) >>> a >>> [1,2,3,1,5,5,5,6]
4) index >>>a.index(3) >>> 2
5) insert >>>a.insert(3, ‘college’)
>>> a >>>[1,2,3, ‘college’,1,5,5,5,6]
6) pop # to remove an element and returns it # by default the last element
>>>a. pop(3) >>> ‘college’ >>>a >>>[1,2,3,1,5,5,5,6]
Sulaiman M.K, Assistant Professor of Physics, Govt. College
4
Malappuram
a = [1,2,3,4, ‘a’]
7) remove # to remove the first occurrence of a value
>>> a.remove(2) >>> a >>> [1,3,4, ‘a’]
8) del >>> del a[2] >>>a >>> [1,3, ‘a’]
9) reverse # reverses the elements in the list
>>>a.reverse( ) >>>a >>> [‘a’,3,1]
10) sort # by default sort in ascending order of ASCII values
# if argument is reverse = True, then sort in Descending order
>>> a.sort( ) >>>a >>> [1,3,’a’]
>>>a.sort(reverse=True) >>>a >>> [‘a’,3,1]
sorted ( ) # This function useful on any sequence, but always returns a list
>>> sorted(a) >>> [1,3, ‘a’]
>>> sorted('college’) >>>['c', 'e', 'e', 'g', 'l', 'l', 'o']

Sulaiman M.K, Assistant Professor of Physics, Govt. College


5
Malappuram
11) len( ) # a function, but internally defined as a method hence
considered as method for list
>>>a=[1,1,3,5,6] >>>len(a) >>>5
12) max( ) >>> max(a) >>>6 # for numerical list
13) min( ) >>>min(a) >>>1 # for numerical list
14) sum( ) >>> sum(a) >>>16 # sum of numeric list values
15) list( ) # to convert tuple or string into a list

Sulaiman M.K, Assistant Professor of Physics, Govt. College


6
Malappuram
Module-1:
Introduction to
Python Programming
(Lecture-7)
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Tuples
• Compound data type like the lists
• Tuples are immutable
• They are set of elements enclosed by parenthesis ( ) and separated by ,
>>> a= (1, ‘a’, 4,5,[1,2])
>>> a = 1, ‘a’, 4,5,[1,2]
• Tuple and list are inter convertible using list( ) and tuple( ) functions
• Indexing and slicing are possible
• Concatenation and repetition are also possible
• len( ) and membership operators are possible

Sulaiman M.K, Assistant Professor of Physics, Govt. College


2
Malappuram
Dictionaries
• Dictionaries are data types with {key:value} pairs enclosed in curly
bracket and separated by comma
• Elements in dictionary are indexed using keys
• Keys are unique and can be almost any type, but commonly
numbers or strings and Values can be any type
>>>a={1: ‘Govt', 2: ‘aided', 3: ‘self'} or
>>> a={} # empty dictionary
>>> a[1]=‘Govt’ >>> a[2]=‘aided'
>>> a[3]=‘self ’
>>> a
{1: ‘Govt', 2: ‘aided', 3: ‘self'}
Sulaiman M.K, Assistant Professor of Physics, Govt. College
3
Malappuram
• There is no ordering concept in dictionary
They are generally used for telephone directory with phone
number as key and name as value or address book with name as
key and address as values

>>>tele_direct={9747: ‘A’, 9946: ‘B’, 9288: ‘C’}


>>>address={‘a’: ‘K puram Post’, ‘b’: ‘RK street’}
>>>address[‘a’]
‘K puram Post’
>>>address[‘b’]
‘RK street’

Sulaiman M.K, Assistant Professor of Physics, Govt. College


4
Malappuram
Dictionary Functions and Methods
Functions
1)len(dict) # number of key value pairs

2)str(dict) # returns a printable string representation of dictionary

>>>str(a)
“{1: ‘Govt', 2: ‘aided', 3: ‘self ’}”

3)type (dict)

Sulaiman M.K, Assistant Professor of Physics, Govt. College


5
Malappuram
Dictionary Methods
dict.items( ) # returns list of tuples of key value pairs
>>> a.items( )
[(1, 'sarbtm'), (2, 'madappally'), (3, 'arts')]
dict.keys( ) # returns keys
>>> a.keys()
[1, 2, 3]
dict.values( )
>>> a.values( )
['sarbtm', 'madappally', 'arts']

Sulaiman M.K, Assistant Professor of Physics, Govt. College


6
Malappuram
Module-1:
Introduction to
Python Programming
(Lecture-8)
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Sets
• Unordered collection of immutable elements and they can not be indexed
>>> a=[1, 2, 3]
>>> b=set(a)
{1, 2, 3}
• There are two types of sets
• 1) set ( ) – mutable set
• 2) frozenset( ) – immutable set
>>> c=frozenset (a)
>>> c
frozenset({1, 2, 3})
Sulaiman M.K, Assistant Professor of Physics, Govt. College
2
Malappuram
Set Functions
1) Membership test: x in s and x not in s
will return True or False

s=set([1,2,3,4,’a’]) g=set([1,2,3,4,5,7,’b’,’c’,’a’])

2) s.issubset(g) # check whether all elements of s are in g


3) s.issuperset(g) #check whether all elements of g are in s
4) s.union(g) # union of a and g, but a does not modify
5)s.intersection(g) #provides intersection of s and g, but s does not modify
Sulaiman M.K, Assistant Professor of Physics, Govt. College
3
Malappuram
6) s.difference(g) #will return set of elements in s, but not in g
7) s.symmetric_difference(g) #will return set of elements in s and g,
#but not in both
8) s.add(x) # will modify set s with adding element x
9) s.remove(x) #will modify set s with removing element x
10) s.copy() # make a copy of s which is not varied by changes in s

Sulaiman M.K, Assistant Professor of Physics, Govt. College


4
Malappuram
Module-1:
Introduction to
Python Programming
(Lecture-9)
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Conditionals
• Conditional execution is important for programming
• if, else, elif commands are used
a=int(input('Enter an integer : ‘))
if a>10:
print ('Integer is greater than 10’)
elif a<10:
print ('Integer is less than 10’)
else:
print (' a is equal to 10’)
Sulaiman M.K, Assistant Professor of Physics, Govt. College
2
Malappuram
Iteration and Looping: while loop
• while <condition>:
<set of statements to do>
<set of statements to do>
Example:
a=10
while a<20:
print (a, a**2)
a=a+1

Sulaiman M.K, Assistant Professor of Physics, Govt. College


3
Malappuram
Iteration and Looping: for loop
• for <variable> in sequence:
<set of statements to do>
<set of statements to do>

>>> for i in [1,2,10]:


print i, i**2, i**3
111
248
10 100 1000
Sulaiman M.K, Assistant Professor of Physics, Govt. College
4
Malappuram
Break and Continue
• break statement to exit from the loop
• continue statement to skip the remaining lines in the block and
to continue the loop from the beginning
>>> a=1
>>> a=1 >>> while a<10:
>>> while a<10: a=a+1
a=a+1 if a==5:
if a==5:
break continue
print (a,a*10) print (a,a*10)
2 20
3 30
4 40
2 20 6 60
3 30 7 70
4 40 8 80
Sulaiman M.K, Assistant Professor of Physics, Govt. College 9 90
5
Malappuram
10 100
Module-1:Introduction to python
Programming
(Lecture-10)
FUNCTIONS, MODULES AND
FILE INPUT/OUT PUT
METHODS
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
User Defined Functions
• A function is a block of code that performs a specific task
• During programming we calls the functions
• Two methods for creating functions in python
• def and lambda
• def
• General format def <name of function>(arg1,arg2,…):
<statement
to perform some thing>
return

Sulaiman M.K, Assistant Professor of Physics, Govt. College


2
Malappuram
>>> def largestnumber(a,b,c):
return max([a,b,c])
>>> largestnumber(10,20,6)
20
lambda
• Not needed to give a name for the function
• Suitable when it is used only in a single file
>>> g=lambda x,y,z:(x**2+y**2+z**2)**.5
>>> g(2,3,4)
5.385164807134504
Or
>>> (lambda x,y,z:(x**2+y**2+z**2)**.5) (2,3,4)
5.385164807134504
Sulaiman M.K, Assistant Professor of Physics, Govt. College
3
Malappuram
Modules
• In python functions, variables and constants may be saved in a python
file and such files are known as modules
• e.g. math, numpy, os, random, pylab etc.
• Functions, variables and constants from a module is used in a program after
importing
• Generally in a particular module related/similar functions, variables and
constants are saved
Import may be in two ways
• 1) import < module name>
• 2) from <module name> import *

Sulaiman M.K, Assistant Professor of Physics, Govt. College


4
Malappuram
# Fibonacci numbers module and save with name mymodule.py
def fib(n): # write Fibonacci series up to n
result=[]
a, b = 0, 1
while b < n:
a, b = b, a+b
result.append(a)
return result
def myconstant( ):
return 4*3.1415*10**-7

Sulaiman M.K, Assistant Professor of Physics, Govt. College


5
Malappuram
Execution in shell

>>> from mymodule import *


>>> fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> myconstant( )*1000
0.0012565999999999999

Sulaiman M.K, Assistant Professor of Physics, Govt. College


6
Malappuram
File Input and Output
• Only strings are stored using inbuilt file input/output method
• Functions used are open( ), write( ), read( ) and close( )
>>> a=open('hello.txt','w')
>>> a.write('I am a student')
14
>>> a.write('I study physics')
15
>>> a.close( )
>>> b=open('hello.txt','r')
>>> b.read( )
'I am a studentI study physics300'
>>> b.close( )
Sulaiman M.K, Assistant Professor of Physics, Govt. College
7
Malappuram
Pickling
• Numbers and other data types can not be
directly stored using inbuilt file input/output
Commands

• Pickle module provides functions for storing any kind of data type
• Important functions used are open ( ), close ( ), load( ), dump ( ) etc.

Sulaiman M.K, Assistant Professor of Physics, Govt. College


8
Malappuram
>>> from pickle import *
>>> f=open('hai.dat','wb')
>>> dump(100,f)
>>> dump([1,2,'eh'],f)
>>> dump('I am a student',f)
>>> f.close()
>>> g=open('hai.dat','rb')
>>> load(g)
100
>>> load(g)
[1, 2, 'eh']
>>> load(g)
'I am a student’
>>> g.close()
Sulaiman M.K, Assistant Professor of Physics, Govt. College
9
Malappuram
Module-2: Numpy and Matplotlib
modules
(Lecture-11)
Arrays and Matrices
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
NumPy Module or Package
• Arrays
• Arrays are main class of NumPy Package and is called ndarray
• It is a table of same data type, usually numbers
• Each element of the array and its shape is indexed by tuple of positive integers
>>> a=array([1,2,3]) ; #dimension 1 or rank 1
>>> a
array([1, 2, 3])
>>> b=array([[1,2],[2,3]]) ; # dimension 2 or rank 2
>>> b
array([[1, 2],
[2, 3]]) Sulaiman M.K, Assistant Professor of Physics Govt. College
2
Malappuram
Array Creation
 a=array([1,2,3])
array( ) function creates an one dimensional array from sequence
array( ) function creates an two dimensional array from sequence of
sequences

>>> a=array([[1,2,3],[1,3,5]])
>>> a
array([[1, 2, 3],
[1, 3, 5]])

Sulaiman M.K, Assistant Professor of Physics Govt. College


3
Malappuram
arange(i,j,p) # arange([start,]stop[,step,], dtype=None)
>>> arange(1,30,3)
array([ 1, 4, 7, 10, 13, 16, 19, 22, 25, 28])

>>> arange(2,50,5,dtype=float)
array([ 2., 7., 12., 17., 22., 27., 32., 37., 42., 47.])
>>> arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> arange(1,10,1.5)
array([ 1. , 2.5, 4. , 5.5, 7. , 8.5])

Sulaiman M.K, Assistant Professor of Physics Govt. College


4
Malappuram
linspace(i,j,n) # linspace(start, stop[,number of elements])
By default the number of elements is 50
>>> linspace(1,20,3)
array([ 1. , 10.5, 20. ])
zeros(shape,dtype=float) # By default the dtype is float64
>>> zeros((2,3),dtype=int)
array([[0, 0, 0],
[0, 0, 0]])
>>> zeros((2,3,4))
array([[[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]],

[[ 0., 0., 0., 0.],


[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]]]) Sulaiman M.K, Assistant Professor of Physics Govt. College
5
Malappuram
>>> zeros(10)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
ones(shape,dtype=None)
>>> ones((2,3))
array([[ 1., 1., 1.],
[ 1., 1., 1.]])
>>> ones(10)
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
>>> ones((2,2),dtype=int)
array([[1, 1],
[1, 1]])
Sulaiman M.K, Assistant Professor of Physics Govt. College
6
Malappuram
• identity(n,dtype=None)
• >>> identity(3)
• array([[ 1., 0., 0.],
• [ 0., 1., 0.],
• [ 0., 0., 1.]])

• >>> identity(3,dtype=int)
• array([[1, 0, 0],
• [0, 1, 0],
• [0, 0, 1]])

Sulaiman M.K, Assistant Professor of Physics Govt. College


7
Malappuram
Matrix
• Similar to array the class matrix can be created using mat(data,dtype=) and
matrix(data,dtype= )
• Where data can be list, tuple, array or string
>>> mat((1,2,3)) #similarly the matrix( ) function
matrix([[1, 2, 3]])
>>> mat([1,2,3])
matrix([[1, 2, 3]])
>>> mat(array([1,2,3]))
matrix([[1, 2, 3]])
>>> mat(('s','a','b'))
matrix([['s', 'a', 'b']],
dtype='|S1') Sulaiman M.K, Assistant Professor of Physics Govt. College
8
Malappuram
Module-2: Numpy and Matplotlib
modules
(Lecture-12)
FUNCTIONS
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Attributes of Array and Matrices
• a=array([[1,2,3],[3,4,5]])
• >>> a.ndim #gives rank or dimension of the array
•2
• >>> a.shape # returns the shape of the array
• (2, 3)
• >>> a.size # return the total number of elements in all dimensions
•6
• >>> a.dtype # returns the data type of the elements
• dtype('int32')

Sulaiman M.K, Assistant Professor of Physics Govt. College


2
Malappuram
Array and Matrix Modification
• >>> a
• array([[1, 2, 3],
• [2, 4, 6]])
• >>> a.ravel( ) # returns the one dimensional array with all elements and
no permanent change to the array
• array([1, 2, 3, 2, 4, 6])
• >>> a=arange(9)
• >>> a
• array([0, 1, 2, 3, 4, 5, 6, 7, 8])
• >>> a.reshape(3,3) # returns the reshaped array, but no permanent change
• array([[0, 1, 2],
• [3, 4, 5],
• [6, 7, 8]])
• >>> a
• array([0, 1, 2, 3, 4, 5, 6, 7, 8])
Sulaiman M.K, Assistant Professor of Physics Govt. College
Malappuram
3
• >>> a
• array([0, 1, 2, 3, 4, 5, 6, 7, 8])
• >>> a.resize(3,3) # reshape permanently
• >>> a
• Array ([[0, 1, 2],
• [3, 4, 5],
• [6, 7, 8]])
• >>> a
• array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
• >>> a.resize((4,3))
• >>> a
• array([[ 0, 1, 2],
• [ 3, 4, 5],
• [ 6, 7, 8],
• [ 9, 10, 11]])
• >>> a.transpose( ) # returns the transpose, no permanent change
• array([[ 0, 3, 6, 9],
• [ 1, 4, 7, 10],
• [ 2, 5, 8, 11]]) Sulaiman M.K, Assistant Professor of Physics Govt. College
4
Malappuram
Basic Arithmetic Operations
• All operations are element wise
>>> a =array ([[0, 1], >>> a
[2, 3]]) array([[1, 2],
>>> b= array ([[2, 3], [1, 2]])
[4, 5]]) >>> b
>>> a+b matrix([[1, 2],
array([[2, 4], [1, 2]])
[6, 8]]) >>> a*a
>>> a-b array([[1, 4],
array([[-2, -2], [1, 4]])
[-2, -2]]) >>> b*b
>>> a*b
matrix([[3, 6],
array([[ 0, 3],
[3, 6]])
[ 8, 15]])
Sulaiman M.K, Assistant Professor of Physics Govt. College
5
Malappuram
>>> a =array ([[0, 1], >>> 3+a
[2, 3]]) array([[3, 4],
>>> b= array ([[2, 3], [5, 6]])
[4, 5]]) >>> 4*a
>>> a/b array([[ 0, 4],
array([[0, 0], [ 8, 12]])
[0, 0]])
>>> a%b
>>> b/a
array([[0, 1],
array([[0, 3],
[2, 3]])
[2, 1]])
>>> b%a
>>> a<5
array([[0, 0],
array([[ True, True],
[ True, True]], dtype=bool) [0, 2]])
Sulaiman M.K, Assistant Professor of Physics Govt. College
6
Malappuram
>>> a
>>> a.sum()
array([[0, 1],
6
[2, 3]])
>>> a.prod()
>>> b
0
array([[2, 3],
>>> b.prod()
[4, 5]])
120
>>> a**2
>>> a.mean()
array([[0, 1],
1.5
[4, 9]])
>>> b.mean()
>>> a**b
3.5
array([[ 0, 1],
>>> a.var()
[ 16, 243]])
1.25
>>> sin(a)
>>> a.std()
array([[ 0. , 0.84147098],
1.1180339887498949
[ 0.90929743, 0.14112001]])
Sulaiman M.K, Assistant Professor of Physics Govt. College 7
Malappuram
Cross Product
➢Gives ordinary cross product for one dimensional vectors
>>> a
array([0, 1, 2])
>>> b
array([2, 3, 4])
>>> cross(a,b)
array([-2, 4, -2])
𝒊 𝒋 𝒌
𝟎 𝟏 𝟐
𝟐 𝟑 𝟒

Sulaiman M.K, Assistant Professor of Physics Govt. College


8
Malappuram
Dot Product
➢>>> a
➢array([0, 1, 2, 3, 4, 5])
➢>>> b
➢array([2, 3, 4, 5, 6, 7])
➢>>> dot(a,b)
➢85

Sulaiman M.K, Assistant Professor of Physics Govt. College


9
Malappuram
Linalg (Linear Algebra)
• linalg is a subpackage of numpy det(a) # to find the determinant and for
• It is to be imported as import numpy.linalg any shape the last two must be square
type
• All are equally applicable to arrays and >>> b
matrices
array([[[ 0, 1],
norm(a) # σ 𝒙𝟐𝒊 [ 2, 3]],
>>> a=arange(12)
>>> from numpy.linalg import * [[ 4, 5],
>>> norm(a) [ 6, 7]],
22.494443758403985
[[ 8, 9],
[10, 11]]])
>>> det(b)
array([-2., -2., -2.])

Sulaiman M.K, Assistant Professor of Physics Govt. College


10
Malappuram
inv(a) # to find the inverse #or can solve(A,Y) #to solve the linear
use a.I equations with coefficient matrix A
and Constant Matrix Y i.e. A X = Y,
>>> b=arange(12).reshape(3,2,2) the find X
>>> inv(b) >>> a=arange(9).reshape(3,3)+4
array([[[-1.5, 0.5], >>> y=arange(3)
[ 1. , 0. ]], >>> a
array([[ 4, 5, 6],
[[-3.5, 2.5], [ 7, 8, 9],
[ 3. , -2. ]], [10, 11, 12]])
>>> y
array([0, 1, 2])
[[-5.5, 4.5],
>>> solve(a,y)
[ 5. , -4. ]]])
array([ 0.91666667, 0.16666667, -0.75])
Sulaiman M.K, Assistant Professor of Physics Govt. College
11
Malappuram
Module-2: Numpy and Matplotlib
modules
(Lecture-13)
PLOTTING
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Matplotlib Module
 Matplotlib is a plotting library for the Python
Visual representations of data like graph, charts, pie diagram etc.
 matplotlib.pyplot is a submodule of python containing all important
functions related to plotting
pylab is another module which contain important functions of both
numpy and matplotlib.pyplot and gets installed along with matplotlib
The data for plotting is supplied as lists or array or tuple

Sulaiman M.K, Assistant Professor of Physics Govt. College


2
Malappuram
Important Functions
• plot(x,y)# to plot graph between x and y data
• plot(x,y,color= ,linestyle= ,marker= ,markerfacecolor= , markersize= )
• >>> from pylab import *
• >>> x=arange(10)
• >>> y=x**2
• >>> x
• array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
• >>> y
• array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81])
• >>> plot(x,y)
• [<matplotlib.lines.Line2D object at 0x060ED270>]
• >>> show()
show( # Send graphics to the output screen
Sulaiman M.K, Assistant Professor of Physics Govt. College
3
Malappuram
>>>plot(x,y,color='g',linestyle='—’,marker='*',markerfacecolor='b',markersize=30)
[<matplotlib.lines.Line2D object at 0x063CA930>]
>>> show( )

Sulaiman M.K, Assistant Professor of Physics Govt. College


4
Malappuram
>>> xlabel('x values')
<matplotlib.text.Text object at 0x05F53730>
>>> ylabel('x ** 2')
<matplotlib.text.Text object at 0x061BABD0>
>>> title('Simple plot ')
<matplotlib.text.Text object at 0x060C6A70>
>>> plot(x,y,color='g',linestyle='--',marker='*',markerfacecolor='b',markersize=30)
[<matplotlib.lines.Line2D object at 0x060E0C70>]
>>> show( )

Sulaiman M.K, Assistant Professor of Physics Govt. College


5
Malappuram
>>> plot(x,y)
[<matplotlib.lines.Line2D object at 0x06341090>]
>>> plot(x,x**3)
[<matplotlib.lines.Line2D object at 0x06341D50>]
>>> show()
#So the legend needs to identify the curves
legend(names, loc= ) # names may be list or tuple of strings
# and loc may be 0,1,2,3,4 etc. 0 represents the most convenient position
>>> legend(['x **2','x**3'],loc=0)
<matplotlib.legend.Legend object at 0x063E0770>
>>> show()
#loc=1 represents upper right, loc=2 represents upper
left and then in anticlockwise

Sulaiman M.K, Assistant Professor of Physics Govt. College


6
Malappuram
• >>> grid(True)
• >>> axis([0,10,10,100]) #[xmin,xmax,ymin,ymax]
• [0, 10, 10, 100]
• >>> show()
• axis(‘off ’) #removes axis
• axis(‘equal’) # equal increment of x and y axis
• text(x,y,string) # x and y are position coordinates
• where of the text to be appeared and string is the text
• >>> plot(x,y)
• [<matplotlib.lines.Line2D object at 0x063D90F0>]
• >>> text(2,20,'Note the position')
• <matplotlib.text.Text object at 0x063D97F0>
• >>> show( )

Sulaiman M.K, Assistant Professor of Physics Govt. College


7
Malappuram
Multiple Plots
• 1) Simple way is to plot functions more than once and then show( )
• 2) figure(num, figsize = (w, h), dpi = N, facecolor =′ b′, edgecolor =′ k′)
• #w,h are width and height in inches, dpi represents the dot per inch resolution,
facecolor represents the background color and edgecolor represents the edge
colour

Sulaiman M.K, Assistant Professor of Physics Govt. College


8
Malappuram
• >>> x=arange(10)
• >>> y1=x**2
• >>> y2=x**3
• >>> figure(1,figsize=(3,5),dpi=600,facecolor='g',edgecolor='k')
• <matplotlib.figure.Figure object at 0x055C30F0>
• >>> plot(x,y1)
• [<matplotlib.lines.Line2D object at 0x06317C30>]
• >>> figure(2,figsize=(5,5),dpi=300,facecolor='b',edgecolor='w')
• <matplotlib.figure.Figure object at 0x05EB5BD0>
• >>> plot(x,y2)
• [<matplotlib.lines.Line2D object at 0x06352470>]
• >>> show()

Sulaiman M.K, Assistant Professor of Physics Govt. College


9
Malappuram
Sulaiman M.K, Assistant Professor of Physics Govt. College
10
Malappuram
Line Styles and Markers marker
"."
description
point
"," pixel
"o" circle
"v" triangle_down
"^" triangle_up
"<" triangle_left
">" triangle_right
"8" octagon
"s" square
"p" pentagon
"*" star
"h" hexagon1
"+" plus
"x" x
"D" diamond
"d" thin_diamond
Sulaiman M.K, Assistant Professor of Physics Govt. College
11
Malappuram
3)subplot(m,n,N) # m - number of rows of subplots, n- number of columns of
subplots, and N – Number of total subplots
>>> subplot(2,2,1)
>>> plot(x,y1)
>>> title('x **2')
>>> subplot(2,2,2)
>>> title('x**3')
>>> subplot(2,2,3)
>>> plot(x,y2)
>>> title('x**3')
>>> subplot(2,2,4)
>>> plot(x,x**4)
>>> title('x**4')
>>> show( )
Sulaiman M.K, Assistant Professor of Physics Govt. College
12
Malappuram
Module-2: Numpy and Matplotlib
modules
(Lecture-14)
PLOTTING
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Multiple Plots
• 1) Simple way is to plot functions more than once and then show( )
• 2) figure(num, figsize = (w, h), dpi = N, facecolor =′ b′, edgecolor =′ k′)
• #w,h are width and height in inches, dpi represents the dot per inch resolution,
facecolor represents the background color and edgecolor represents the edge
colour

Sulaiman M.K, Assistant Professor of Physics Govt. College


2
Malappuram
• >>> x=arange(10)
• >>> y1=x**2
• >>> y2=x**3
• >>> figure(1,figsize=(3,5),dpi=600,facecolor='g',edgecolor='k')
• <matplotlib.figure.Figure object at 0x055C30F0>
• >>> plot(x,y1)
• [<matplotlib.lines.Line2D object at 0x06317C30>]
• >>> figure(2,figsize=(5,5),dpi=300,facecolor='b',edgecolor='w')
• <matplotlib.figure.Figure object at 0x05EB5BD0>
• >>> plot(x,y2)
• [<matplotlib.lines.Line2D object at 0x06352470>]
• >>> show()

Sulaiman M.K, Assistant Professor of Physics Govt. College


3
Malappuram
3)subplot(m,n,N) # m - number of rows of subplots, n- number of columns of
subplots, and N – Number of total subplots
>>> subplot(2,2,1)
>>> plot(x,y1)
>>> title('x **2')
>>> subplot(2,2,2)
>>> title('x**3')
>>> subplot(2,2,3)
>>> plot(x,y2)
>>> title('x**3')
>>> subplot(2,2,4)
>>> plot(x,x**4)
>>> title('x**4')
>>> show( )
Sulaiman M.K, Assistant Professor of Physics Govt. College
4
Malappuram
Sulaiman M.K, Assistant Professor of Physics Govt. College
5
Malappuram
Line Styles and Markers marker
"."
description
point
"," pixel
"o" circle
"v" triangle_down
"^" triangle_up
"<" triangle_left
">" triangle_right
"8" octagon
"s" square
"p" pentagon
"*" star
"h" hexagon1
"+" plus
"x" x
"D" diamond
"d" thin_diamond
Sulaiman M.K, Assistant Professor of Physics Govt. College
6
Malappuram
Module-2: Numpy and Matplotlib
modules
(Lecture-15)
PLOTTING
18 Hours

Sulaiman M.K, Assistant Professor of Physics, Govt. College


1
Malappuram
Polar Plots

➢ polar(theta, radius, keywords) # theta is angle in radian with respect to origin


>>> theta=linspace(0,2*pi,200)
>>> r=2*cos(theta)
>>> polar(theta,r,color='g',linestyle='--',marker='*',markerfacecolor='y')
>>> show( )

Sulaiman M.K, Assistant Professor of Physics Govt. College


2
Malappuram
Plotting sin(x) and cos(x)
>>> from pylab import *
>>> x=linspace(0,2*pi,200)
>>> plot(x,sin(x))
>>> plot(x,cos(x))
>>> legend(['sin(x)','cos(x)'])
>>> show()

Sulaiman M.K, Assistant Professor of Physics Govt. College


3
Malappuram
log (x)
>>> from pylab import *
>>> x=linspace(0,2*pi,200)
>>> plot(x,exp(x))
>>> show( )

Sulaiman M.K, Assistant Professor of Physics Govt. College


4
Malappuram
sin(x**2) and (sin(x))**2
>>> from pylab import *
>>> x=linspace(0,4*pi,1000)
>>> plot(x,(sin(x))**2)
>>> plot(x,sin(x**2))
>>> legend(['(sin(x))**2','sin(x**2)'])
>>> show( )

Sulaiman M.K, Assistant Professor of Physics, Govt. College


5
Malappuram
Pi Charts (Out of Syllabus)
• It is the chart in which a circle is divided into sectors as per the values
• pie(fracs, labels=[labs])
>>> fract=[10,30,20,80,150]
>>> labs=['A','B','C','D','E']
>>> pie(fract,labels=labs)
>>> show( )

Sulaiman M.K, Assistant Professor of Physics Govt. College


6
Malappuram
CURVE FITTING
LEAST SQUARES CURVE FITTING

Sulaiman M.K.
Assistant Professor
Department of Physics, Govt. College Malappuram

Courtesy: Introductory Methods of Numerical Analysis by S.S. Sastry


Curve Fitting
• Process of fitting a curve on the data which are subject to errors
• Here we find the expression that fits the data with least errors
• i.e. if we are given set of data (xi,yi), i=1,2,3….n, we fit the function y=f(x).
• Where y=mx+c for the straight line fit
• Here by fitting the curve means, finding the coefficients m and c
Least Squares Curve Fitting
• In Least Squares Curve Fit, we minimize the sum of squares of
the errors, and hence the name
• i.e. if we are given the data (xi,yi), i=1,2,3….n and we have to fit
the curve f(x)
• Then the error for each value will be ei=[yi-f(xi)]
• Then sum of squares of the errors will be
S=[y1-f(x1)]2+[y2-f(x2)]2+[y3-f(x3)]2+[y4-f(x4)]2…………+[yn-f(xn)]2

= e12+ e2 2+ e3 2+ e4 2+……………+ en 2
• Now we will minimize the S
Straight Line Fitting
• For straight line fitting, we take the equation of the straight line as f(x)
i.e. f(x)=a0+a1x
• We chose in this form because we can easily then extend to higher order polynomial
by adding higher terms
• The sum of squares of errors when fitting this expression on the data (xi,yi),
i=1,2,3….n will be

S=[y1-f(x1)]2+[y2-f(x2)]2+[y3-f(x3)]2+…………+[yn-f(xn)]2
=[y1-(a0+a1x1)]2+[y2-(a0+a1x2)]2+[y3-(a0+a1x3)]2+…………+[yn-(a0+a1xn)]2

𝝏𝑺 𝝏𝑺
• To minimize S, we set =𝟎 ; = 𝟎 and find the coefficients a0 and a1
𝝏a 0 𝝏a 𝟏
𝝏𝑺
= −2[y1−(a0+a1x1)]−2[y2−(a0+a1x2)]−2[y3−(a0+a1x3)]−…………−2[yn−(a0+a1xn)]
𝝏a 0
=-2σ𝑛𝑖=1[𝑦𝑖 − (𝑎0 + 𝑎1 𝑥𝑖 )]
=-2[(y1+y2+…yn)-(𝑎0 +𝑎0 +….+𝑎0 )-a1(x1+x2+….+xn)]=0

i.e. n𝑎0 +a1(x1+x2+….+xn)=(y1+y2+…yn)

Similarly

𝝏𝑺
= −2x1[y1−(a0+a1x1)]−2x2[y2−(a0+a1x2)]−2x3[y3−(a0+a1x3)]−…………−2xn[yn−(a0+a1xn)]
𝝏a𝟏
=-2[(x1y1+x2y2+…+xnyn)-𝑎0 (x1+x2+….+xn)-a1(x12+x22+….+xn2)]=0

i.e. 𝑎0 (x1+x2+….+xn)+a1(x12+x22+….+xn2)=(x1y1+x2y2+…+xnyn)
n𝑎0 +a1(x1+x2+….+xn)=(y1+y2+…yn)

𝑛𝑎0 + 𝑎1 ෍ 𝑥𝑖 = ෍ 𝑦𝑖

𝑎0 (x1+x2+….+xn)+a1(x12+x22+….+xn2)=(x1y1+x2y2+…+xnyn)

2
𝑎0 ෍ 𝑥𝑖 +𝑎1 ෍ 𝑥𝑖 = ෍ 𝑥𝑖 𝑦𝑖

• From the above equations, we can find the coefficients easily by


Cramer’s rule
σ 𝑦𝑖 σ 𝑥𝑖 𝑛 σ 𝑦𝑖
2
σ 𝑥𝑖 𝑦𝑖 σ 𝑥𝑖 σ 𝑥𝑖 σ 𝑥𝑖 𝑦𝑖
𝑎0 = and 𝑎1 =
𝑛 σ 𝑥𝑖 𝑛 σ 𝑥𝑖
2 2
σ 𝑥𝑖 σ 𝑥𝑖 σ 𝑥𝑖 σ 𝑥𝑖
Assignment
• Find the best values of a0 and a1 if the straight-line
Y=a0+a1x is fitted to the data (xi,yi):

(1,4.5),(2,7.8),(5,10.8),(8,15),(10,20)
LEAST SQUARES CURVE FIT
LINEAR FIT ILLUSTRATION
WITH PYTHON

SULAIMAN MK
Assistant Professor of Physics
Govt. College Malappuram

Courtesy: Introductory Methods of Numerical Analysis by S.S. Sastry.


Problem
• Find the best values of a0 and a1 if the straight line
Y=a0+a1x is fitted to the data (xi,yi):
(1,4.5),(2,7.8),(5,10.8),(8,15),(10,20)

• Also write the python code to solve the above and plot the
fitted curve
Linear Least Square Curve Fit Equations

𝑛𝑎0 + 𝑎1 ෍ 𝑥𝑖 = ෍ 𝑦𝑖
2
𝑎0 ෍ 𝑥𝑖 +𝑎1 ෍ 𝑥𝑖 = ෍ 𝑥𝑖 𝑦𝑖

σ 𝑦𝑖 σ 𝑥𝑖 𝑛 σ 𝑦𝑖
2
σ 𝑥𝑖 𝑦𝑖 σ 𝑥𝑖 σ 𝑥𝑖 σ 𝑥𝑖 𝑦𝑖
𝑎0 = and 𝑎1 =
𝑛 σ 𝑥𝑖 𝑛 σ 𝑥𝑖
2 2
σ 𝑥𝑖 σ 𝑥𝑖 σ 𝑥𝑖 σ 𝑥𝑖
Python Produced Table
Python Program For Printing Data Table
#printing table least squares fit
x=array([1,2,5,8,10])
y=array([4.5,7.8,10.8,15,20])
print ('-’*70)
print ('%20s\t%10s\t%10s\t%10s'%( 'x', 'y','x*x','x*y’))
print ('-’*70)
for i in range(5):
print ('%20.2f\t%10.2f\t%10.2f\t%10.2f'%(x[i],y[i],x[i]**2,x[i]*y[i]))
print ('-’*70)
print ('sum=%10.2f\t%10.2f\t%10.2f\t%10.2f'%(sum(x),sum(y),sum(x**2),sum(x*y)))
print ('-’*70)
Python Produced Table
Python Code for Solution
from pylab import *
x=array([1,2,5,8,10])
y=array([4.5,7.8,10.8,15,20])
d=array([len(x),sum(x),sum(x),sum(x**2)]).reshape(2,2)
d1=array([sum(y),sum(x),sum(x*y),sum(x**2)]).reshape(2,2)
d2=array([len(x),sum(y),sum(x),sum(x*y)]).reshape(2,2)
from numpy.linalg import *
a0=det(d1)/det(d)
a1=det(d2)/det(d)
print ('y=',a0,'+',a1,'x’) y= 3.4857142857142853 + 1.5642857142857152 x
plot(x,y,'*')
f=a0+a1*x
plot(x,f)
xlabel('x values')
ylabel('y values')
title('Least Squares Linear Fit')
show( )
y= 3.4857142857142853 + 1.5642857142857152 x
BISECTION METHOD
WITH PYTHON CODE

SULAIMAN MK
Assistant Professor of Physics
Govt. College Malappuram
ROOT OF A FUNCTION?

• Root of a function f(x) means the value (or values) of x for which f(x)=0

Courtesy: https://images.app.goo.gl/nmcw5HG4BRF96a5s5 and https://images.app.goo.gl/uTEypWdfBW4kYppa9


BISECTION METHOD
Backbone Theorem
• If a function f(x) is continuous between a and b, and f(a) and f(b)
are of opposite signs, then there exists at least one root between a
and b

Method
• We reduce the root containing interval to so small as that we need
the accuracy
• i.e. we bisect the interval, then find the root containing interval
from the two new intervals and proceed like this
Steps

• Find a and b such that f(a) and f(b) are of opposite signs
(we assume f(a) is –ve and f(b) is +ve for the convenience )
• Now root lies between a and b
(𝒂+𝒃)
• Find 𝒙𝟎 = and check whether f(𝒙𝟎 ) is +ve or –ve
𝟐
• If f(𝒙𝟎 ) is +ve, then f(𝒙𝟎 ) and f(a) are of opposite signs
• Hence root lies between a and 𝒙𝟎
• This continues till the interval reduces to our desired accuracy
Example
Problem: Find one of the roots of the equation x3-x-1=0 correct to
4 decimal points
Solution:
• Initially we find two points a and b, for which f(a) and f(b) are of
opposite signs
• We select a=1; f(a)=f(1)=-1 and b=3; f(b)=f(3)=23
(𝒂+𝒃) (𝟏+𝟑)
• Next find 𝒙𝟎 = = = 𝟐; f(2)=5
𝟐 𝟐
• So now root lies between a=1 and 𝒙𝟎 = 𝟐
• i.e. we replace b by 𝒙𝟎 or new a=1 and b=2
• And proceeds till the interval reduces to 0.00001 or less
----------------------------------------------------------------------------------------------------

n a b x0 f(x0)
----------------------------------------------------------------------------------------------------
0 1.00000000 3.00000000 2.00000000 5.00000000
1 1.00000000 2.00000000 1.50000000 0.87500000
2 1.00000000 1.50000000 1.25000000 -0.29687500
3 1.25000000 1.50000000 1.37500000 0.22460938
4 1.25000000 1.37500000 1.31250000 -0.05151367
5 1.31250000 1.37500000 1.34375000 0.08261108
6 1.31250000 1.34375000 1.32812500 0.01457596
7 1.31250000 1.32812500 1.32031250 -0.01871061
8 1.32031250 1.32812500 1.32421875 -0.00212795
9 1.32421875 1.32812500 1.32617188 0.00620883
10 1.32421875 1.32617188 1.32519531 0.00203665
11 1.32421875 1.32519531 1.32470703 -0.00004659
12 1.32470703 1.32519531 1.32495117 0.00099479
13 1.32470703 1.32495117 1.32482910 0.00047404
14 1.32470703 1.32482910 1.32476807 0.00021371
15 1.32470703 1.32476807 1.32473755 0.00008355
16 1.32470703 1.32473755 1.32472229 0.00001848
17 1.32470703 1.32472229 1.32471466 -0.00001406
----------------------------------------------------------------------------------------------------

the root=1.3247
----------------------------------------------------------------------------------------------------
Python for Bisection Method
#Bisection method
while 1:
a,b=input('enter the interval a,b:')
def f(x):
return x**3-x-1
if f(a)*f(b)<0.0:
print'-'*100
print'\nn \ta\t \tb\t \tx\t \tf(x)'
print'-'*100
i=0
while abs(a-b)>=0.00001:
x=(a+b)/2.0
print'%d\t%.8f\t%.8f\t%.8f\t%.8f'%(i,a,b,x,f(x))
i=i+1
if f(x)*f(a)>0.0:
a=x
else:
b=x
print'-'*100
print'\n the root=%.4f'%a
print'-'*100
break
else:
print'no roots in this interval'
print'enter another interval'
----------------------------------------------------------------------------------------------------

n a b x0 f(x0)
----------------------------------------------------------------------------------------------------
0 1.00000000 3.00000000 2.00000000 5.00000000
1 1.00000000 2.00000000 1.50000000 0.87500000
2 1.00000000 1.50000000 1.25000000 -0.29687500
3 1.25000000 1.50000000 1.37500000 0.22460938
4 1.25000000 1.37500000 1.31250000 -0.05151367
5 1.31250000 1.37500000 1.34375000 0.08261108
6 1.31250000 1.34375000 1.32812500 0.01457596
7 1.31250000 1.32812500 1.32031250 -0.01871061
8 1.32031250 1.32812500 1.32421875 -0.00212795
9 1.32421875 1.32812500 1.32617188 0.00620883
10 1.32421875 1.32617188 1.32519531 0.00203665
11 1.32421875 1.32519531 1.32470703 -0.00004659
12 1.32470703 1.32519531 1.32495117 0.00099479
13 1.32470703 1.32495117 1.32482910 0.00047404
14 1.32470703 1.32482910 1.32476807 0.00021371
15 1.32470703 1.32476807 1.32473755 0.00008355
16 1.32470703 1.32473755 1.32472229 0.00001848
17 1.32470703 1.32472229 1.32471466 -0.00001406
----------------------------------------------------------------------------------------------------

the root=1.3247
----------------------------------------------------------------------------------------------------
NEWTON-RAPHSON METHOD
WITH PYTHON CODE

SULAIMAN MK
Assistant Professor of Physics
Govt. College Malappuram
Newton-Raphson Method
• Let x0 be an approximation root of f(x) =0 and let x1=x0+h be the correct root, i.e. f(x1)=0.
• We can expand f(x0+h) by Taylor series,
f(x0 +h)=f(x0)+hf ' (x0)+(h2 /2)f '' (x0)+…… =0
• Neglecting the second and higher order derivatives
Therefore f(x0 +h)=f(x0)+hf ' (x0)=0 ; hence h = - [f(x0)/ f ' (x0)]
𝒇 𝒙𝟎
𝒙𝟏 = 𝒙𝟎 −
𝒇 ′ 𝒙𝟎
𝒙𝟐 = 𝒙𝟏 − [𝒇(𝒙𝟏)/ 𝒇 ′ (𝒙𝟏)]

………………….
𝒙𝒏+𝟏 = 𝒙𝒏 − [𝒇(𝒙𝒏)/ 𝒇 ‘(𝒙𝒏)]
Convergence Condition

• Let 𝒙𝒏+𝟏 = 𝝋 (𝒙𝒏)

𝝋 (xn) = xn -[f(xn)/ f ' (xn)]

Hence 𝝋′(x)=[ f(x)f ''(x)]/[f ' (x)f ' (x)]

Convergence condition is |𝝋′(x)| <1


Program
#NEWTON-RAPHSON METHOD
from math import*
def f(x):
return sin(x)-2*x+1
def f1(x):
return (f(x+dx)-f(x))/dx
dx=.001
x=float(input("Guess the root: "))
while abs(f(x))>0.00001:
x=x-f(x)/f1(x)
print ("The root is",x)
Program with Convergence Condition
#NEWTON-RAPHSON METHOD
from math import*
def f(x):
return sin(x)-2*x+1
def f1(x):
return (f(x+dx)-f(x))/dx
def f2(x):
return (f1(x+dx)-f1(x))/dx
dx=.001
while (1):
x=float(input("Guess the root: "))
if abs((f(x)*f2(x))/(f1(x)**2))<1:
while abs(f(x))>0.00001:
x=x-f(x)/f1(x)
print ("The root is",x)
break

You might also like