Fundamentals of Python and Numerical Methods
Fundamentals of Python and Numerical Methods
B.Sc. V SEM|GPY5B06T
COMPUTATIONAL PHYSICS
Edited by
Prince Alex
Department of Physics
St. Joseph’s College Devagiri, Calicut-673008
SYLLABUS (54 hrs)
Unit 1
Chapter 1: Introduction to Python Programming 16 Hours
Introduction to algorithm, flowchart and high level Computer programming languages Compilers-
Interpreters - Introduction to Python language- Advantages and unique features of Python language -
Interactive mode and script mode- Writing and execution of programs -various data types in Python-
Reading keyboard input: The raw_input function and input function - print command, formatted
printing- open and write function - Variables, operators, expressions and statements-String operations,
Lists, list operations ( len, append, insert, del, remove, reverse, sort, +, *, max, min, count, in, not in,
sum), sets, set operations (set, add, remove, in, not in, union, intersection, symmetric difference)-Tuples
and Dictionaries, various control and looping statements: (if, if..else, if..ellif, while, for, break, continue)
- user defined functions- Modules - File input and file output-Pickling.
Numpy module: Introduction, creation of arrays and matrices, various array operations, matrix
multiplication, inversion. Matplotlib module: Introduction, plot( ), show( ) functions, syntax for plotting
graphs , multiple plots, polar plots, labeling, scaling of axes and coloring plots - Plotting of functions –
sin(x), cos(x), exp(x), sin2(x), sin(x2).
Unit 2
Chapter 3: Numerical Methods in Physics 18 Hours
Introduction to numerical methods, Comparison between analytical and numerical methods – Curve
Fitting: Principle of least squares, Least square fitting of a straight line -Interpolation: Finite difference
operator, Newton's forward difference interpolation formula, difference table, First and second
derivative by Numerical differentiation- Solution of algebraic equations: Bisection method, Newton-
Raphson method - Newton Cote's quadrature formula- Numerical integration by Trapezoidal and
Simpson's (1/3) method- Solution of differential equations: Euler's method, Runge-Kutta method
(Second order) -Taylor's Series expansion of Sin(x) and Cos(x).
Unit 3
Chapter 4: Computational Physics 14 Hours
Formulation: From analytical to numerical methods -Significance of Computer in numerical methods-
Applications of Euler's method: Theory, and graphical simulation by programming: motions of a freely
falling body, a body dropped into a highly viscous medium, two dimensional projectile motion and
1
radioactive decay - Accuracy considerations (elementary ideas) ( All programs should be written using
Python language Version 3.0)
References
1. Introduction to Python for Engineers and Scientists by Dr.Sandeep Nagar, Apress publications.
2. Python for Education by Dr. B P Ajithkumar, IUAC, New Delhi; e-book freely downloadable
from www.expeyes.in/documents/mapy.pdf
3. Python Tutorial Release 3.0.1 by Guido van Rossum, Fred L. Drake, Jr., editor.
(http://www.altaway.com/resources/python/tutorial.pdf).
4. Introductory methods of numerical analysis, S.S.Shastry , (Prentice Hall of India,1983).
5. Numerical Methods in Engineering and Science, Dr. B S Grewal, Khanna Publishers,
New Delhi (or any other book)
2
Contents
1 Chapter-1: Core python .................................................................................................................. 8
1.1 Free Software .......................................................................................................................... 8
1.2 High Level Languages and Machine Languages ...................................................................... 8
1.3 Programming steps ................................................................................................................. 9
1.4 Compilers vs Interpreter ......................................................................................................... 9
1.5 Python ..................................................................................................................................... 9
1.6 IDLE (Integrated Development and Learning Environment)/IDE/text editor ....................... 10
1.6.1 Python IDLE ................................................................................................................... 10
1.6.2 PyCharm ........................................................................................................................ 11
1.6.3 Jupyter Notebook.......................................................................................................... 12
1.6.4 Spyder ........................................................................................................................... 14
1.7 Different Modes of Using Python ......................................................................................... 15
1.7.1 Calculator Mode (Interactive Mode) ............................................................................ 16
1.7.2 File Mode (Script Mode) ............................................................................................... 16
1.8 Variables (identifier), keywords and constants .................................................................... 17
1.9 Data types ............................................................................................................................. 18
1.9.1 Numeric Data Type ....................................................................................................... 19
1.9.2 Mathematical functions ................................................................................................ 22
1.9.3 String ............................................................................................................................. 26
1.9.4 List ................................................................................................................................. 30
1.9.5 Tuples ............................................................................................................................ 35
1.9.6 Set ................................................................................................................................. 36
1.9.7 Dictionary ...................................................................................................................... 38
1.9.9 Sequence ....................................................................................................................... 40
1.9.10 Type () function ............................................................................................................. 40
1.10 Operators .............................................................................................................................. 43
1.10.1 Arithmetic Operators .................................................................................................... 43
1.10.2 Assignment operators ................................................................................................... 45
1.10.3 Logical operator ............................................................................................................ 47
1.10.4 Comparison (Relational) Operators .............................................................................. 48
1.10.5 Bitwise Operators ......................................................................................................... 50
1.10.6 Membership Operators................................................................................................. 52
1.10.7 Identity Operators......................................................................................................... 53
1.11 General Operator Precedence .............................................................................................. 53
3
1.12 Expressions and Statements ................................................................................................. 55
1.12.1 Arithmetic Expressions and Statements ....................................................................... 55
1.12.2 Input and Output Statements ....................................................................................... 56
1.13 Control Structure/ Control Flow ........................................................................................... 68
1.13.1 Sequential ..................................................................................................................... 68
1.13.2 Selection structure (conditional structure)/Decision control statement or branching
statement. ..................................................................................................................................... 68
1.13.3 Repetitive structure ...................................................................................................... 76
1.13.4 Modify loops: break and continue ................................................................................ 89
1.13.5 For loop with enumerate function ................................................................................ 90
1.13.6 For loop with zip function ............................................................................................. 90
1.14 Functions ............................................................................................................................... 91
1.15 Local Variables ...................................................................................................................... 99
1.16 Global statement .................................................................................................................. 99
1.17 Modules .............................................................................................................................. 100
1.17.1 Import module ............................................................................................................ 100
1.17.2 import module as alias (alternate name).................................................................... 101
1.17.3 from module import *................................................................................................. 102
1.17.4 From module import selected definitions .................................................................. 102
1.18 User defined Modules ......................................................................................................... 103
1.19 Data files (File input and output)(Read from a file and Write to a file) ............................. 106
1.19.1 Writing to a file ........................................................................................................... 107
1.19.2 Reading a file ............................................................................................................... 108
1.19.3 Appending data to file................................................................................................. 110
1.20 Pickling (The pickle module) ............................................................................................... 110
1.20.1 Write a file using pickle ............................................................................................... 111
1.20.2 Read the data using pickle .......................................................................................... 111
1.21 Pandas (Not a part of syllabus) ........................................................................................... 112
1.22 Assignment-1: Model Questions......................................................................................... 119
1.23 Assignment-II:: Model questions ........................................................................................ 121
2 Chapter-2: The numpy and pylab modules................................................................................. 134
2.1 The NumPy Module ............................................................................................................ 134
2.2 Creating Arrays and Matrices.............................................................................................. 134
2.2.1 array () ......................................................................................................................... 135
2.2.2 arrange (start, stop, step, datatype) ........................................................................... 137
2.2.3 linspace (start, stop, number of elements)................................................................. 138
4
2.2.4 zeros (shape, datatype)............................................................................................... 140
2.2.5 ones (shape, datatype) ............................................................................................... 141
2.2.6 Random number array ................................................................................................ 141
2.2.7 identity(shape) ............................................................................................................ 143
2.2.8 reshape (array, newshape) ......................................................................................... 143
2.3 Indexing, slicing and iterating one-dimensional array ........................................................ 144
2.4 Copying array ...................................................................................................................... 144
2.5 Various array operations..................................................................................................... 145
2.5.1 Arithmetic operations ................................................................................................. 145
2.5.2 Matrix operations ....................................................................................................... 146
2.6 Exercise ............................................................................................................................... 153
2.7 Basic statistical operations.................................................................................................. 153
2.8 Matplotlib module .............................................................................................................. 154
2.8.1 Plot simple x and y data .............................................................................................. 155
2.8.2 Subplot ........................................................................................................................ 165
2.8.3 Plotting sin (x), cos (x), sin2 (x) and sin (x2) .................................................................. 176
2.8.4 Polar plots (Archimedes spiral, Fermat’s spiral, Polar rose) ....................................... 182
2.8.5 Exponential plot .......................................................................................................... 187
2.9 Previous year questions ...................................................................................................... 188
2.10 Model questions ................................................................................................................. 189
2.11 APPENDIX (Not for exam).................................................................................................. 189
3 Chapter-3: Numerical Methods-I ................................................................................................ 204
3.1 Analytical and Numerical Methods ..................................................................................... 204
3.1.1 Analytical Methods: .................................................................................................... 204
3.1.2 Numerical Methods: ................................................................................................... 204
3.1.3 Differences between analytical and numerical methods: .......................................... 205
3.2 Advantages of numerical methods over analytical methods. ............................................ 205
3.3 Solution(root) of algebraic equation................................................................................... 206
3.3.1 Bisection method ........................................................................................................ 206
3.3.2 Newton-Raphson method........................................................................................... 212
3.4 Curve fitting: Principle least square-straight line fitting ..................................................... 218
3.5 Interpolation ....................................................................................................................... 225
3.5.1 Finite difference .......................................................................................................... 226
3.5.2 Forward difference ..................................................................................................... 226
3.5.3 Forward difference table ............................................................................................ 227
3.5.4 Newton’s forward interpolation formula ................................................................... 227
5
3.6 Numerical differentiation: Formula for derivatives ............................................................ 235
3.7 Numerical integration ......................................................................................................... 239
3.7.1 Newton-cotes quadrature formula ............................................................................. 240
3.7.2 Trapezoidal rule .......................................................................................................... 241
3.7.3 Simpson’s 1/3 rule ...................................................................................................... 241
3.8 Numerical solution of ordinary differential equation ......................................................... 248
3.8.1 Euler method............................................................................................................... 248
3.8.2 Ruge-Kutta (RK) method second order (modified Euler method) .............................. 249
3.9 Taylor series expansion of sin(x) and cos (x)....................................................................... 254
4 Computational Methods in Physics and Computer Simulations ................................................ 258
4.1 What is computational Physics? ......................................................................................... 258
4.2 Importance of Python simulation in Physics....................................................................... 259
4.3 Advantage and disadvantages of using computational techniques for physical problems.
260
4.4 Classical Mechanics: 1D simulations ................................................................................... 261
4.4.1 Simulation of a freely falling body (Euler’s method) .................................................. 261
4.4.2 Motion of a body dropped into a heavily viscous medium (Euler’s method) ............ 265
4.5 Classical Mechanics: 2D simulation .................................................................................... 268
4.5.1 Projectile motion (Using Euler’s method) ................................................................... 268
4.6 Monte Carlo simulations ..................................................................................................... 278
4.6.1 Radioactive decay ....................................................................................................... 278
5 Chapter-1: Model question ......................................................................................................... 280
6 Previous year questions .............................................................................................................. 298
6
Chapter-1
Introduction to Python Programming
7
1 Chapter-1: Core python
Python is a free software
Free software is computer software that is distributed along with its source code, and is released under
terms that guarantee users the four levels of freedom. They are
Free software is often developed cooperatively by volunteer computer programmers as part of an open-
source software development project.
The term "free software" was coined in 1985 by Richard Stallman, during the founding of the GNU
project (a collaborative effort to create a freedom-respecting operating system) and the Free Software
Foundation (FSF). The FSF's Free Software Definition states that users of free software are "free"
because they do not need to ask for any permission; and they are not restricted in activities through
restrictive proprietary licenses (e.g. copy-restriction), or requirements of having to agree to restrictive
terms of others (e.g. non-disclosure agreements), and they are not already restricted from the outset (e.g.
through deliberate non-availability of source code).
The licencing of Free Software is GPL (The GNU General Public License), generally known as copy-
left in contrast to the stringent copy-right rules. (https://www.gnu.org/copyleft/gpl.html)
The operating system under this licence is the GNU/Linux. This is available as different distributions
like, Ubuntu, Red Hat Linux, Debian, OpenSUSE, Mandrake etc.
8
language must be translated into machine language before being executed by the computer. Such
translators are generally known as compilers or interpreters.
Compiler: Using this the source file is converted into machine language (executable/binary) in a single
step. The syntax checking is done during this process. After successful compilation, the binary is
produced and it can be executed when needed.eg. C, C++, FORTRAN etc
Interpreter: Using this, the source file is executed statement by statement. Each statement is converted
to binary on the go. On any syntax error the execution will be stopped. Hence source code is need for
execution. Hence modification and debugging can be done easily. But slower compared to Interpreted
language. The main advantage is its simplicity. Eg Python, BASIC etc
1.5 Python
Python is rapidly developing and widely used general-purpose high level language. It is an interpreted
language with all the required features of other languages like C, C++, Java, FORTRAN, List, Cobol
etc. This beautiful language is the creation of Guido van Rossum. It appeared for the first time in 1991
and the name python was inspired from a BBC comedy series ‘Monty pythons flying circus’.
Python has different versions. After version 2.7 (Old python) a new series is started for 3.0 and now
reached at version 3.3. There are small differences between the syntax of version 2.x and 3.x. This
• Python can be downloaded from ‘python.org’. Tick the check box ‘add Python 3.10 to PATH’
during installation.
• To install modules such as numpy and matplotlib, type in the command prompt as shown
below
• To install numpy, type ‘pip install numpy’ in the command prompt as shown below and press
enter where pip stands for python installation package
10
• Similarly, to install matplot library, type ‘pip install matplotlib’ in the command prompt and
enter
•
1.6.2 PyCharm
To install modules, go to file new project setup settings for new project
11
• Click “+” and type the module you want and install
12
• It will open a page in your default browser as shown below
13
1.6.4 Spyder
• Same as jupyter notebook, go to anaconda prompt, type ‘spyder’ or directly open from
anaconda navigator. It will open a window as shown below
14
Google colab eric Vim
Thonny geany
Python interpreter is available freely for Linux as well as windows platforms. Even though the use of
Python in Linux is given, the same can be used with windows also. In windows, one can use softwares
like IDLE, Visual studio etc. for this. IDLE can be downloaded from www.python.org
Python Can be used in two modes One method is to enter commands in Python interpreter shell. This
mode is known as Calculator mode. The second approach is like any other program. A source file is
created and it is executed with the help of the python interpreter.
15
1.7.1 Calculator Mode (Interactive Mode)
In calculator mode we can call a python shell and different commands can be entered in a python
prompt.
Result will be obtained immediately after a command is entered. This is very useful when we learn
python or we have very simple programs (which has a few statements!) To get a python shell, open a
terminal in Linux and type the command python there, the python interpreter will become active by
showing a python prompt (>>>). This prompt is known as python primary prompt.
When the program becomes very long or complicated the calculator mode becomes very inconvenient.
Also the same program cannot be used later in the previous method. Hence it has to be stored as a file
and this file is executed with the help of python interpreter.
For this a file consisting of the statements is created with the help of a text editor like vim, gedit, notepad
etc. This is saved with a suitable name with extension as .py. This is executed using python
interpreter in the Linux terminal. Alternatively different IDEs (Integrated Development and Learning
Environment.)
are available for python programming. An IDE integrates all the process like editing file, execution etc.
on a single application busing different menu.
• To go to script mode: Python shell File New file
16
• To run the program → run → run module (shortcut key: fn+f5)
The basic topics you have to understand while learning any high level language in the begining are the
following
Variable: A storage space to store values, called by a name known as an identifier (means to identify
something) or variable name. Unlike languages like C,C++, variables need not be declared at the
beginning. Type of the variable is determined during the assignment of value, known as dynamic typing
(or auto typing). Variable is identified by a variable name. It is a good practice to use meaningful name
for a variable even though it is not mandatory. The following points must be remembered while
choosing a variable name
➢ The first character of the identifier must be a letter of the alphabet (upper or lowercase) or an
underscore ('_').
➢ The rest of the identifier name can consist of letters (upper or lowercase), underscores ('_') or
digits (0-9).
17
➢ Identifier names are case-sensitive. For example, myname and myName are not the same. Note
the lowercase n in the former and the uppercase N in the later.
➢ Examples of valid identifier names are i, __my_name, velocity, mass_electron, x123.
➢ Examples of invalid identifier names are 2things, velocity of light, mass-electron etc.
Consider age of a person is to be entered as a variable. Following are the valid and invalid variables.
Eg Comments
Valid _age Start with a ‘_’
variables age Start with a lower case
Age Start with a upper case
AgE Combination of upper and lower case
age1 Combination of letters and digits
age_1 Combination of letters, digits and ‘_’
age_of_a_persion Combination of words and ‘_’
Invalid 9age Can’t start with a digit
variables age of a person Space in between is not permitted
age+of-a*persion Other symbols are not permitted
lambda Certain list of selected words are not permitted
and Certain list of selected words are not permitted
Keywords: Also Keywords define the language's rules and structure, and they cannot be used as
variable names. It is a good idea to remember the key words so that naming variables will become easy.
Python keywords are
False async elif global lambda return
None await else except nonlocal try
True break except if not while
and class finally import or with
as continue for in pass yield
assert def from is raise
Constants: Constants are whose value doesn't change during the execution of a program. They belong
to one of the data type that we are going to discuss. Assignment operator ( =) is used to assign a constant
to a variable. When a variable is assigned with constant, type of the value (constant) becomes the type
of the variable. All the examples mentioned in the table of data types are examples of constants.
18
1.Numbers (Numeric) Simple data type
2.String
3.List Compound data type (Sequence type)
4.Tuple
5.Set
6.Dictionary
7.Boolean
1.9.1.1 Integers
19
1.9.1.2 Long integer (Only in python 2)
20
IDLE Shell 3.10.4
>>> c=2+3j
>>> c.real
2.0
>>> c.imag
3.0
1. Int(x)
2. long(x)
3. Float (x)
4. Complex(x)
5. Complex (x,y)
Convert the given x and y values into a complex number with real and imaginary part
21
(3+4j)
Some mathematical function requires module ‘math’ module and some not.
Math functions require math module Doesn’t require math module
log(x) cmp(x,y)
fabs(x) abs(x)
log10(x) pow(x,y)
ceil(x) max(x1,x2,x3,------)
floor(x) min(x1,x2,x3,------)
exp(x) round(x)
sqrt(x)
sin(x), cos(x), tan(x)
asin(x),acos(x),atan(x)
Those mathematical functions which require math module need to be imported. A module can be
imported in four different ways. Any one of the following methods can be used to import the module
• import math
• import math as m
• from math import*
• from math import sin,pi
Examples of math functions that require math module are given below
1. log(x)
It will return the natural logarithm that is to the base e
IDLE Shell 3.10.4
>>> import math
>>> x=2
>>> math.log(x)
0.6931471805599453
or module can be imported as follows. Here module name is abbreviated to a letter. Then import it as
shown below
IDLE Shell 3.10.4
>>> import math as m
>>> x=2
>>> m.log(x)
0.6931471805599453
Again, module can be imported in another way as shown below. In this case module name is not
required to be mentioned in front of the math function
IDLE Shell 3.10.4
22
>>> from math import*
>>> x=2
>>> log(x)
0.6931471805599453
A module can be imported with only the specific function that is required as shown below
IDLE Shell 3.10.4
>>> from math import log
>>> x=2
>>> log(x)
0.6931471805599453
For the remaining math function, we will be using the third method here onwards
2. fabs(x)
It will return the absolute value of a given number x into the floating number format. In mathematics
absolute value of a number is the positive value of that number, |-x|=x
IDLE Shell 3.10.4
>>> from math import*
>>> x=-2
>>> fabs(x)
2.0
3. log10(x)
It will return the log to the base 10 of the given number
IDLE Shell 3.10.4
>>> from math import*
>>> x=2
>>> log10(x)
0.3010299956639812
4. Ceil (x)
Ceiling of x. It will return the next largest integer value of the given number
IDLE Shell 3.10.4
>>> from math import*
>>> x=5.6
>>> ceil(x)
6
5. floor (x)
23
6. exp (x)
Exponential of x. It will return the exponential value of the given number, eg. e3
IDLE Shell 3.10.4
>>> from math import*
>>> x=3
>>> exp(x)
20.085536923187668
1. sqrt (x)
Square root of x. It will return the square root of the given number, eg. sqrt(4)=2
IDLE Shell 3.10.4
>>> from math import*
>>> x=4
>>> sqrt(x)
2.0
It will return the trigonometric values of the function sin, cos and tan (measured in radians). To enter
the values in angle, divide the value by 57.3 (1 𝑟𝑎𝑑𝑖𝑎𝑛 = = 57.3)
angle 0 30 45 60 90
sin 0 ½=0.5 1/√2=1.414 √3/2=0.866 1
cos 1 √3/2=0.866 1/√2=1.414 ½=0.5 0
tan 0 1/√3=1.732 1 √3=1.732 ∞
24
0.9999999999999999
Examples of math functions that doesn’t require math module are given below
1. abs(x)
It will return the absolute value of a given number x into the floating number format. In mathematics
absolute value of a number is the positive value of that number, |-x|=x
IDLE Shell 3.10.4
>>> x=-2
>>> abs(x)
2
3. pow(x,y)
it returns the value as xy
25
IDLE Shell 3.10.4
>>> x=2
>>> y=4
>>> pow(x,y)
16
4. max(x), min(x)
It returns the maximum and minimum when x is a set of values
5. round(x)
It returns the closest integer value of the given floating number
1.9.3 String
26
String can also used in the following way where string is defined outside the print statement as shown
below
IDLE Shell 3.10.4
>>> str='python programming using IDLE shell'
>>> print(str)
python programming using IDLE shell
H e l l o w e l c o m e t o p y t h o n
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
- - - -9 -8 -7 -6 -5 -4 -3 -2 -1
print(str) Hello welcome to python
print(str[0]) h (first letter of the string)
print(str[-1]) n (first letter from last)
print(str[2:5]) llo (from 2nd index string till 5th index string, not including 5th)
print(str[2:]) llo welcome to python (2nd index location to last, including last)
print(str[:6]) Hello (from 0th index string till 6th, not including 6th index)
print(str[-7:-1]) python (from -7th index string till -1th string, not incluing -1)
print(str[-7:]) python (from -7th index string to last, including last)
print(str[0:22:2] Hlowloet yh (every alternative letters from 0th till last, not including last)
)
print(str[1:22:3] eoeo t (from 1st index string till last not including last with an interval of 3)
)
27
>>> print(str[0:22:2])
Hlowloet yh
>>> print(str[1:22:3])
eoeo t
➢ Python has a set of built-in methods that you can use on strings
Here the above example programs are written in file mode as shown in the first panel below. The file is
saved by giving a name ‘String_built_in_functions.py’. After Run→Run Module, the result
can be viewed in Python IDLE shell as shown in the second panel
28
String_built_in_functions.py
1 str='Programming in python using python IDLE shell'
2 print(str)
3 print(str[::-1])
4 print(str.lower())
5 print(str.upper())
6 print(str.swapcase())
7 print(str.title())
8 print(str.replace('python','pycharm'))
9 print(str.replace('python','pycharm',1))
10 print(str.replace('python','pycharm',2))
11 print(str.replace('python','',2))
Concatenation operation
>>>str1=’welcome’ All the three strings will be combined without
>>>str2=’to’ any space in between
>>>str3=’python’
>>>str4=str1+str2+str3
welcometopython
>>>str1=’welcome ’ An empty space is added before closing the
>>>str2=’to ’ inverted comma
>>>str3=’python’
>>>str4=str1+str2+str3
Welcome to python
>>>str1=’welcome’ A null string (‘ ’) is added between strings to
>>>str2=’to’ include a space
>>>str3=’python’
>>>str4=str1+’ ’+str2+’ ’+str3
Welcome to python
Repetition operation
>>>str1=’python’ Str1 will be repeated trice
29
>>>str2=str1*3
>>>print(str2)=pythonpythonpython
1.9.4 List
➢ A list contains items separated by commas and enclosed within square brackets - [ and ].
➢ To some extent, lists are similar to arrays in C. One difference between them is that all the items
belonging to a list can be of different data type.
➢ Lists are Mutable (elements can be changed)
➢ Elements are accessed or modified by index (integer representing position in list, starting from
zero; using the format [ index ])
Eg.
lis1=[1,2,3,4.2,5+3j]
lis2=[1,2.5,10.5+4j,'apple']
List slice operation
We can access elements in the list same as in string
Operation Meaning
>>>print(lis1) Print the string 1
[1, 2, 3, 4.2, (5+3j)]
>>>print(lis2) Print the string 1
[1, 2.5, (10.5+4j), 'apple']
>>>print(lis1[0]) Print the element at the index location 0
1
>>>print(lis1[1]) Print the element at the index location 1
2
>>>print(lis1[-1])
(5+3j)
>>>print(lis1[2:3])
[3]
>>>print(lis1[2:4])
[3, 4.2]
>>>print([lis1+lis2])
[[1, 2, 3, 4.2, (5+3j), 1, 2.5, (10.5+4j), 'apple']]
>>>print(lis1*2)
[1, 2, 3, 4.2, (5+3j), 1, 2, 3, 4.2, (5+3j)]
>>>print([lis1+lis1])
[[1, 2, 3, 4.2, (5+3j), 1, 2, 3, 4.2, (5+3j)]]
IDLEShell 3.10.4
>>> lis1=[1,2,3,4.2,5+3j]
>>> lis2=[1,2.5,10.5+4j,'apple']
>>> print(lis1)
[1, 2, 3, 4.2, (5+3j)]
>>> print(lis2)
[1, 2.5, (10.5+4j), 'apple']
>>> print(lis1[0])
1
>>> print(lis1[1])
30
2
>>> print(lis1[-1])
(5+3j)
>>> print(lis1[2:3])
[3]
>>> print(lis1[2:4])
[3, 4.2]
>>> print([lis1+lis2])
[[1, 2, 3, 4.2, (5+3j), 1, 2.5, (10.5+4j), 'apple']]
>>> print(lis1*2)
[1, 2, 3, 4.2, (5+3j), 1, 2, 3, 4.2, (5+3j)]
>>> print([lis1+lis1])
[[1, 2, 3, 4.2, (5+3j), 1, 2, 3, 4.2, (5+3j)]]
Operations Meaning
list1=[1,3,10.5,’apple’,1,3,1,-5]
list2=[-2+3j,22.2]
list3=[100,2,-5,0,20,48] (only numbers, no strings)
1.append() Add an element at the end of the list
>>>list1.append(‘orange’)
>>>print(list1)
[1,3,10.5,’apple’,1,3,1,-5,’orange’]
2.Insert() Add an element at a specific position
>>>list1.insert(3,'mango')
>>>print(list1)
[1, 3, 10.5, 'mango', 'apple', 1, 3, 1, -5, 'orange']
3.extend() Add the element of a list to another list
>>>list1.extend(list2)
>>>print(list1)
[1, 3, 10.5, 'mango', 'apple', 1, 3, 1, -5, 'orange',
(-2+3j), 22.2]
4.count() Returns the number of elements with specific
>>>list1.count(1) value
3
5.len() Returns the length of the string
>>>len(list1)
12
6.index() Returns the index of the first element with the
>>>list1.index(10.5) specific value
2
7.remove() Remove the item with specific value
>>>list1.remove(10.5)
>>>print(list1)
31
[1, 3, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-
2+3j), 22.2]
8.pop() Remove the element at a specific locations
>>>list1.pop(1)
3
>>>print(list1)
[1, 10.5, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-
2+3j), 22.2]
9.del() Removes a specific element
>>>del list1[1]
>>>print(list1)
[1, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-2+3j),
22.2]
10.clear() Remove all the elements from the list
>>>list1.clear()
>>>print(list1)
[]
>>>list1=[1,3,10.5,'apple',1,3,1,-5]
>>>print(list1)
[1, 3, 10.5, 'apple', 1, 3, 1, -5]
>>>list2=[-2+3j,22.2]
>>>print(list2)
[(-2+3j), 22.2]
11.copy() Returns a copy of the list
>>>b=list1.copy()
>>>print(b)
[1, 3, 10.5, 'apple', 1, 3, 1, -5]
12.reverse() Reverse the order of the list
>>>list1.reverse()
>>>print(list1)
[-5, 1, 3, 1, 'apple', 10.5, 3, 1]
>>>list3=[100,2,-5,0,20,48]
>>>print(list3)
[100, 2, -5, 0, 20, 48]
13.sort() Arrange the elements of the list in the ascending
>>>list3.sort() order
>>>print(list3)
[-5, 0, 2, 20, 48, 100]
14.max() Returns the element with maximum value
>>>max(list3)
100
15.min() Returns the element with minimum value
>>>min(list3)
-5
16.sum() Returns the sum of all the elements of the list
>>>sum(list3)
165
17. + List joining operation
>>>print(list1+list2)
[-5, 1, 3, 1, 'apple', 10.5, 3, 1, (-2+3j), 22.2]
18.* List repletion operation
>>>print(list1*2)
[-5, 1, 3, 1, 'apple', 10.5, 3, 1, -5, 1, 3, 1, 'apple',
10.5, 3, 1]
32
IDLE Shell 3.10.4
>>> list1=[1,3,10.5,'apple',1,3,1,-5]
>>> print(list1)
[1, 3, 10.5, 'apple', 1, 3, 1, -5]
>>> list2=[-2+3j,22.2]
>>> print(list2)
[(-2+3j), 22.2]
>>> list3=[100,2,-5,0,20,48]
>>> print (list3)
[100, 2, -5, 0, 20, 48]
>>> list1.append('orange')
>>> print (list1)
[1, 3, 10.5, 'apple', 1, 3, 1, -5, 'orange']
>>> list1.insert(3,'mango')
>>> print(list1)
[1, 3, 10.5, 'mango', 'apple', 1, 3, 1, -5, 'orange']
>>> list1.extend(list2)
>>> print(list1)
[1, 3, 10.5, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-2+3j), 22.2]
>>> list1.count(1)
3
>>> len(list1)
12
>>> list1.index(10.5)
2
>>> list1.remove(10.5)
>>> print(list1)
[1, 3, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-2+3j), 22.2]
>>> list1.pop(1)
3
>>> print(list1)
[1, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-2+3j), 22.2]
>>> del list1[1]
>>> print (list1)
[1, 'apple', 1, 3, 1, -5, 'orange', (-2+3j), 22.2]
>>> list1.clear()
>>> print(list1)
[]
>>> list1=[1,3,10.5,'apple',1,3,1,-5]
>>> print(list1)
[1, 3, 10.5, 'apple', 1, 3, 1, -5]
>>> b=list1.copy()
>>> print(b)
[1, 3, 10.5, 'apple', 1, 3, 1, -5]
>>> list1.reverse()
>>> print(list1)
[-5, 1, 3, 1, 'apple', 10.5, 3, 1]
>>> list3=[100,2,-5,0,20,48]
>>> print(list3)
[100, 2, -5, 0, 20, 48]
>>> list3.sort()
>>> print(list3)
33
[-5, 0, 2, 20, 48, 100]
>>> max(list3)
100
>>> min(list3)
-5
>>> sum(list3)
165
>>> print(list1+list2)
[-5, 1, 3, 1, 'apple', 10.5, 3, 1, (-2+3j), 22.2]
>>> print (list1*2)
[-5, 1, 3, 1, 'apple', 10.5, 3, 1, -5, 1, 3, 1, 'apple', 10.5, 3, 1]
Saving a list
Script file
arithmetic.py
1 list=[1,4,9,16,25]
2 from numpy import*
3 #import numpy as np*
4 savetxt('storelist.dat',list,fmt='%s')
5 #np.savetxt('storelist.dat',list,fmt='%s')
save this as savelist.py
Folder view
File view
34
1.9.5 Tuples
• A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike list, tuple is enclosed within parentheses ().
• The main difference between tuple and list is that tuple cannot be updated
• Hence tuple can be thought of as read only list(immutable list)
Eg. Tuple1=(0,-20,-7+2j,’apple’,0.02)
• Elements can be accessed by index (integer representing position in tuple, starting from zero,
using the format [])
35
(1, 3, 10.5)
>>> tuple2[3:]
('apple', 1, 3, 1, -5)
>>> tuple2.index(10.5)
2
>>> tuple2.count(1)
3
>>> len(tuple2)
8
>>> tuple2.append('orange')
AttributeError: 'tuple' object has no attribute 'append'
>>> tuple3=(100,2,-5,0,20,48)
>>> len(tuple3)
6
>>> max(tuple3)
100
>>> min(tuple3)
-5
>>> tuple1=(0,-20,-7+2j, 'apple',0.02)
>>> tuple2=(1,3,10.5,'apple',1,3,1,-5)
>>> tuple4=tuple1+tuple2
>>> print(tuple4)
(0, -20, (-7+2j), 'apple', 0.02, 1, 3, 10.5, 'apple', 1, 3, 1, -5)
1.9.6 Set
Set operations
set1={4,2,-2,0,’car’}
set2={-2,’car’,7.5,2+3j}
1.Union() All the elements in set1 and set1
>>>set1.union(set2)
{0, 2, 4, 7.5, (2+3j), 'car', -2}
2.intersection() Common elements in set1 and set2
>>> set1.intersection(set2)
{'car', -2}
3.difference() Only those elements in set1 but not in set2
>>>set1.difference(set2)
{0, 2, 4}
>>>set2.difference(set1) Only those elements in set2 but not in set1
{(2+3j), 7.5}
Built-in operations
set1={4,2,-2,0,’car’}
set2={-2,’car’,7.5,2+3j}
1.add() Add an element to the set
>>> set1.add(4444)
36
>>>print(set1)
{0, 'car', 2, 4, 4444, -2}
2.clear() Remove all the elements from the set
>>>Set1.clear()
3.discard() Remove the specified item
>>>set1.discard('car')
>>>print(set1)
{0, 2, 4, 4444, -2}
4.remove() Remove the specified item (same as discard)
>>>set1.remove(4444)
>>>print(set1)
{0, 2, 4, -2}
It means you cannot repeat an element. In the example given below, element 4 is repeated. But you
print it, the set will allow only one repeated element
37
Hence if you try to add an element similar to an already existing element in a set, that element will not
be added to the list.
1.9.7 Dictionary
Dictionary operation
d={‘rose’:’a flower’,’e’:1.6e-19,’apple’:’a fruit’,1:’a number’}
>>>d[‘e’]
1.6e-19
>>>d[‘rose’]
‘a flower’
1.get() Returns the value of the specified key
>>>d.get(1)
‘a number’
>>>d.get(‘rose’)
‘a flower’
2.pop() Removes the element with a specified key
>>>d.pop(‘rose’)
‘a flower’
3.popitem() Late item will be removed
>>>d.popitem()
4.values() Returns a list of all values in the dictionary
>>>d.values()
5.keys() Returns a list containing the dictionary’s keys
>>>d.keys()
6.update({}) Enter a key-value pair to the set
>>>d.update({‘w’:’a letter’})
7. d[‘age’]=35 New pair will be added (same as update)
8.d.items() All pairs will be displayed
38
>>> d['rose']
'a flower'
>>> d.get(1)
'a number'
>>> d.get('rose')
'a flower'
>>> d.pop('apple')
'a fruit'
>>> d
{'rose': 'a flower', 'e': 1.6e-19, 1: 'a number'}
>>> d.popitem()
(1, 'a number')
>>> d
{'rose': 'a flower', 'e': 1.6e-19}
>>> d.values()
dict_values([1.6e-19, 'a fruit', 'a number'])
>>> d.keys()
dict_keys(['e', 'apple', 1])
>>> d.update({1:'a number'})
>>> d
{'rose': 'a flower', 'e': 1.6e-19, 1: 'a number'}
>>> d['apple']='a fruit'
{'rose': 'a flower', 'e': 1.6e-19, 1: 'a number', 'apple': 'fruit'}
>>> d.items()
dict_items([('rose', 'a flower'), ('e', 1.6e-19), (1, 'a number'),
('apple', 'fruit')])
1.9.8 Boolean
Two type
• True
• False
IDLE Shell 3.10.4
>>> True
True
>>> False
False
>>> True+True
2
>>> True+True+True
3
>>> False+False
0
>>> False+True
1
>>> True*True
1
>>> True*False
39
0
>>> bool(1)
True
>>> bool('abc')
True
>>> bool(22.4)
True
>>> bool(0)
False
The the Boolean value of an argument is true unless it is a zero or a null string, null list, null tuple,
null set or null dictionary
1.9.9 Sequence
A data type which is a collection of elements, and the elements are identified by an integer index is
commonly known as a sequence or an iterable. Eg. String, list and tuple
Type function is used to find the data type of the given data
>>>a=222
>>>type(a)
<class 'int'>
>>>b=10.5
>>>type(b)
<class 'float'>
>>>c=3+4j
>>>type(c)
<class 'complex'>
>>>d=10L Not defined in python 3
>>>type(d)
>>>e=’car’
>>>type(e)
<class 'str'>
>>>f=[1,10,’car’,2.2]
>>>type(f)
<class 'list'>
>>>g=(1,10,’car’,2.2)
>>>type(g)
<class 'tuple'>
>>>h={1,10,’car’,2.2}
>>>type(h)
<class 'set'>
>>>i={1:'a number','w':'a letter'}
>>>type(i)
<class 'dict'>
40
<class 'int'>
>>> b=10.5
>>> type(b)
<class 'float'>
>>> c=3+4j
>>> type(c)
<class 'complex'>
>>> d='car'
>>> type(d)
<class 'str'>
>>> e=[1,10,'car',2.2]
>>> type(e)
<class 'list'>
>>> f=(1,10,'car',2.2)
>>> type(f)
<class 'tuple'>
>>> g={1,10,'car',2.2}
>>> type(g)
<class 'set'>
>>> h={1:'a number','w':'a letter'}
>>> type(h)
<class 'dict'>
41
IDLEShell 3.10.4
>>> List1=[2,4.4,'scooter',2+3j,True]
>>> set1=set(List1)
>>> print(set1)
{2, 4.4, 'scooter', (2+3j), True}
>>> type(set1)
<class 'set'>
Similarly for converting set into tuple and tuple into set
42
• asin(x),acos(x),atan(x)
Doesn’t need math module
• cmp(x,y)
• abs(x)
• pow(x,y)
• max(x1,x2,x3,------)
• min(x1,x2,x3,------)
• round(x)
Tuple Set Dictionary
tup1=(1,3,10.5,’apple’,1,3,1,-5) set1={1,3,10.5,’apple’,1,3,1,- d={1:’anumber’,’w’:’a letter’}
5}
tup1[0] union() get()
tup1[-1] intersection() values()
tup1[2:5] difference() keys()
tup1[3:] add() pop()
tup1[:3] remove() update({})
len() discard()
count() clear()
index()
max()
min()
1.10 Operators
Operators are needed for constructing different expressions. This is used for operating on different data
types. Python language supports following type of operators.
• Arithmetic operator
• Assignment operator
• Logical operator
• Comparison (relational) operator
• Conditional (ternary) operator (same as control structures in the coming section)
• Bitwise operator
• Membership operator
• Identity operator
1.10.1 Arithmetic Operators
43
- Subtraction - Subtracts right hand >>>11-3
operand from left hand operand 8
* Multiplication - Multiplies values on >>>11*3
either side of the operator 33
/ Division - Divides left hand operand by python-3 >>>11/3
right hand operand 3.6666666666666665
python-2 >>>4/3
3
>>>4.0/3.03.6666666666666665
>>>4.0/3
3.6666666666666665
>>>4/3.0
3.6666666666666665
% Modulus - Divides left hand operand >>>11%3
by right hand operand and returns 2
remainder
// Floor Division - The division of >>>11//3
operands where the result is the 3
quotient in which the digits after the
decimal point are removed.
** Exponent - Performs exponential >>>11**3 (113)
(power) 1331
calculation on operators
44
Program-1: Write and execute a program for finding the sum of digits in an integer.
Method: We can extract the last digit from integer using modulus division by 10. We can remove the
last digit using floor division by 10 (python 3.x)(integer division in python 2.x). Using this repeatedly
we can extract the digits and find the sum.
n=4567
d1=n%10=7
n=n//10=456
d2=n%10=6
n=n//10=45
d3=n%10=5
n=n//10=4
d4=n%10=4
sum=d1+d2+d3+d4
print ('sum of digits =',sum)
Script file
Program_1.py
1 n=4567
2 d1=n%10 #4567%10=7, returns the reminder of the operation
3 n=n//10 #4567//10=456, returns the quotient without decimal point
4 d2=n%10 #456%10=6
5 n=n//10 #456//10=45
6 d3=n%10 #45%10=5
7 n=n//10 #45//10=4
8 d4=n%10 #4%10=4
9 sum=d1+d2+d3+d4 #7+6+5+5
10 print ('sum of digits =',sum)
Output
IDLE Shell 3.10.4
>>>
sum of digits = 22
45
-= Subtract It subtracts right operand from >>>c-=a c=c-a
AND the left 7 c=10-7
operand and assign the result to
left operand
*= Multiply It multiplies right operand with >>>c*=a c=c*a
AND the left 30 c=10*3
operand and assign the result to
left operand
/= Divide AND It divides left operand with the >>>c/=a c=c/a
right operand and assign the 3.333333333333 c=10/3
result to left operand
%= Modulus It takes modulus using two >>>c%=a c=c%a
AND operands and assign the result to 1 c=10%3
left operand
//= Floor division It performs exponential (power) >>>c//=a c=c//a
AND calculation on operators and 3 c=10//3
assign value to the left operand
**= Exponent It performs floor division on >>>c**=a c=c**a
AND operators and assign value to the 1000 c=10**3
left operand
Script file
Program_1.py
1 c=10;a=3
2 print('c=',c,'a=',a)
3
4 c+=a
5 print('c+=a:',c)
6
7 c=10;a=3
8 c-=a
9 print('c-=a:',c)
10
11 c=10;a=3
12 c*=a
13 print('c*=a:',c)
14
15 c=10;a=3
16 c/=a
17 print('c/=a:',c)
18
19 c=10;a=3
20 c%=a
46
21 print('c%=a:',c)
22
23 c=10;a=3
24 c//=a
25 print('c//=a:',c)
26
27 c=10;a=3
28 c**=a
29 print('c**=a:',c)
Output
IDLE Shell 3.10.4
>>> c= 10 a= 3
c+=a: 13
c-=a: 7
c*=a: 30
c/=a: 3.3333333333333335
c%=a: 1
c//=a: 3
c**=a: 1000
47
Called Logical OR Operator. If any of the two True
operands is true then then condition becomes true. >>>x>y or a<b
True
>>>xy or a>b
True
>>>x<y or a<b
False
not Called Logical NOT Operator. Use to reverses the >>>not x>y
logical state of its operand. If a condition is true False
then Logical NOT operator will make false. >>>not x<y
True
and or not
>>> x=5;y=3;a=10;b=5
>>> print(x>y and a>b)
True
Operates on two numeric data and return a logical value (True or False)
48
Operator Description Example
>>>a=10; b=20;x=5;y=3;z=5
== Checks if the value of two operands are equal or not, >>>a==b
if yes then condition becomes true. False
>>>x==z
True
!= Checks if the value of two operands are equal or not, >>>a!=b
if values are not equal then condition becomes true. True
>>>x!=z
False
<> Checks if the value of two operands are equal or not, >>>a<>b (only in python 2)
if values are not equal then condition becomes true. True
>>>x<>z (only in python 2)
False
> Checks if the value of left operand is greater than the >>>a>b
value of right operand, if yes then condition becomes False
true. >>>x>y
True
< Checks if the value of left operand is less than the >>>a<b
value of right operand, if yes then condition becomes True
true. >>>x<y
False
>= Checks if the value of left operand is greater than or >>>x>=y
equal to the value of right operand, if yes then True
condition becomes true. >>>x>=z
True
>>>a>=b
False
<= Checks if the value of left operand is less than or >>>x<=y
equal to the value of right operand, if yes then False
condition becomes true >>>x<=z
True
>>>a<=b
True
49
False
>>> a==b
False >>> x>=z
True
>>> x==z
True >>> x>=y
True
>>> a!=b
True >>> a>=b
False
>>> x!=z
False >>> x<=y
False
>>> a>b
False >>> x<=z
True
>>> x>y
True >>> a<=b
True
>>> a<b
True
>>> x<>z
False
Consider two decimal numbers 60 and 13, corresponding binaries are 0011 1100 and 0000 1101
a=0011 1100
b=0000 1101
AND operation OR operation XOR
0011 1100 (AND) 60 0011 1100 (OR) 60 0011 1100 (XOR) 60
0000 1101
13 0000 1101 13 0000 1101 13
0000 1100
12 0011 1101 61 0011 0001 49
1’s complement left shift two bit rigth shift two bit
0011 1100 + 1’s 0011 1100 0011 1100
1
com 001111 00 00 111100
-00111101
60 1111 0000 = 240 0000 1111 =15
Is -61
50
1’s complement note
a = 60 = 0011 1100
1’s com of 60 = 1100 0011
To get the negative of a number in binary, we take the 2’s complement of that number
Here to get -61, we take 2’s complement of 61
61 = 0011 1101
1’s com of 61 =1100 0010
51
| Binary OR Operator copies a bit if it exists in >>>a|b
either operand. 61
^ Binary XOR Operator copies the bit if it is set in >>>a^b
one operand but not both. 49
~ Binary Ones Complement Operator is unary and >>>~a
has the effect of 'flipping' bits. -61
<< Binary Left Shift Operator. The left operands >>>a<<2
value is moved left by the number of bits specified 240
by the right operand. >>>a<<1
120
>> Binary Right Shift Operator. The left operands >>>a>>2
value is moved right by the number of bits 15
specified by the right operand. >>>a>>1
30
In addition to the operators discussed previously, Python has membership operators, which test for
membership in a sequence, such as strings, lists, or tuples.
52
True
not in Evaluates to true if it does not find a variable in >>>a not in list
the specified sequence and false otherwise. True
>>>b not in list
False
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below:
53
Operator Description
** Exponentiation (raise to the power)
Complement, unary plus and minus (method
~+- names for the last two are +@
and -@)
*, /, %, // Multiply, divide, modulo and floor division
+ ,- Addition and subtraction
>>, << Right and left bitwise shift
& Bitwise 'AND'
^ ,| Bitwise exclusive `OR' and regular `OR'
<=, < >, >= Comparison operators
==, != Equality operators
=,%=,/=,//=,-=,+=,*=,**= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
Operator Description
** Exponentiation
+, – Addition, subtraction
^ Bitwise XOR
I Bitwise OR
54
Operator Description
or Logical OR
Operators summary
Arithmetic Assignment Logical Comparison Bitwise Membership Identity
operators operators operators operators operators operators operators
= and == & in is
+ += or != | not in is not
- -= not <> ^
* *= > ~
/ /= < <<
% %= >= >>
// //= <=
** **=
55
Eg; a**2+2*a*b+c, when a=2, b=3 and c=4
a**2+2*a*b+c=20
➢ Evaluation of an arithmetic expression is done according to the precedence of operators.
➢ Change of precedence can be achieved using parentheses. Expression inside the parentheses
will be evaluated first. In case of nested parentheses innermost pair of parentheses will be done
first and so on.
Eg.(a+b)*c/d
(a+b)*(c/d)
((a+b)*c)/d
a+(b*c)/d
When the value of the arithmetic expression is assigned to a variable using one of the assignment
statements we get an arithmetic statement. Simple examples of these are:
x=10
area = 3.141*a**2
velocity = distance/time
Just to start writing simple program it is necessary to know the different statements to display the
result on the screen to take inputs from a key board. The output statement can be formed with the
keyword print.
Print difference between python 2.x and python 3.x: print keyword in Python 2.x is replaced by the
print() function in Python 3.x. Parentheses is must in python 3.x but optional in python 2.x
>>> print(2)
2
56
Print statements are of two types, unformatted and formatted
1.12.2.1.1 Unformatted Output (Print) Statements
The simplest method is using unformatted print statement, which is very simple. The usage is print
followed by the constants or variables or expressions whose value must be printed by separating with
coma. For example
>>>x=2
>>> print(x) #variable
2
>>>print (2)
2 #constant
>>>print(2+4) #expression
6
>>>print(2,3) #seperated by comma
2 3
>>>a,b,c=2,3,5
>>>print(a,b,c)
2 3 5
>>>print(10,2.5,’car’)
10 2.5 car
57
Displaying multiple output and multiple string in the output statement
IDLE Shell 3.10.4
>>> a=2;b=2+3j; c=-22.2
>>> print('a=',a,'b=',b,'c:',c)
a= 2 b= (2+3j) c: -22.2
In all the above examples we discussed the print statement to get output on screen in the unformatted
way. Hence all the values will be printed as it is. For example, consider the of printing the result of 10/3
using unformatted way
>>> print(10/3)
3.3333333333333335
Most often in this type of an output, all the decimal digits are neither good looking nor required. Suppose
we require only the number correct up three decimal places only. This can be achieved using formatted
printing. Consider we use the print command like the one below.
>>> a=10.0/3.0
>>> print "%7.3f" % (a)
3.333
You can see that the number is printed with three decimal digits. The general method of formatted
printing is done by using a format string followed by the % operator and the values to be printed as a
tuple – all values inside a pair of ( ), separated by commas. with exactly the
number of items specified by the format string.
Format string: the format string is constructed with any string with format specifiers at the required
position, i.e. the position in the string we expect the values to be printed. For example, assume the case
of finding the sum of two numbers. See formatted output works in this case.
>>>a,b=2,3
>>>c=a+b
>>>print 'Sum of %d and %d is %d' % (a,b,c)
Sum of 2 and 3 is 5. The format specifier %d is for integers while %f is used for floats. The format
specifiers for various data types are given below.
58
Format General
Data Type Explanation
Specifier format
Decimal d %wd
w is optional
Integer Octal o %wo w is the total fields required for printing
Hexadecimal x %wx
Fractional f %wn.f w.n is optional
Float
Exponential e %wn.e n is the number of decimal places required
string s %ws w is optional
w is the total fields required for printing
\n for a new line
\t for tab space
Example Description
>>>print('%d' % (15)) %d is the format specifier for
15 decimal number 15
>>>print('%10d' % (15)) 15 is printed after 10 letter space
15
>>>print('%10d %d' % (15,234000)) Since two numbers have to be
15 234000 printed two format specifier is used.
>>>print('%10d %10d %10d' % (15,234000,3.14141414)) Three format specifiers are used.
15 234000 3 Though the third number is a
floating number, its format specifier
is given as decimal. Hence this
number will be printed as integer
instead of floating
>>>print('%10d %10d %10f' % (15,234000,3.14141414)) Two decimal and one floating
15 234000 3.141414 format specifier
>>>print('%10d %10d %10.2f' % (15,234000,3.14141414))
15 234000 3.14
>>>print('%10d %10d %7.4f' % (15,234000,3.14141414))
15 234000 3.1414
>>>print('%10o %10d %7.4f' % (15,234000,3.14141414)) First format specifier is for octal
17 234000 3.1414 number, here decimal number 15 is
converted into octal number 17
using format specifier
>>>print('%10x %10d %7.4f' % (15,234000,3.14141414)) First format specifier is
f 234000 3.1414 hexadecimal
>>>print('%10d %10e %7.4f' % (15,234000,3.14141414)) Second format specifier is for
15 2.340000e+05 3.1414 exponential number
>>>print('%10d %10.2e %7.4f' % (15,234000,3.14141414))
15 2.34e+05 3.1414
59
>>>print('He bought a %s colored %s' %('red','car')) Format specifier for string
He bought a red colored car
>>>print('hello world')
hello world
>>>print('hello \nworld') New line
hello
world
>>>print('hello \n world') Second line will start after a letter
hello space
world
>>>print('hello \tworld') Tab space
hello
>>>print('hello \t world')
hello world
60
Hello
world
>>> print('Hello \n world')
Hello
world
>>> print('Hello \tworld')
Hello world
>>> print('Hello \t world')
Hello world
Formatting string
Data can be given to a program using two methods (Python 2.7). The basic method is to assign the
required data to variable in the program itself using assignment statements. Another method to give
data while a program is running is to use input statements in the program. When the program is
executed, the computer will wait for input when the input statement is executed. The user can type the
data through the keyboard and press the return (enter) key to submit the data to the program.
The input() function in Python is used to take input from the user. When this function is called, the
program stops and waits for the user to type something on the keyboard. Once the user presses the Enter
key, the input is read as a string and returned by the function.
61
input() and raw_input () are the two functions used for this purpose. These two works in different way
in python 2.x and python 3.x.
Python 2.x: This is used to input a single string as the input. Whatever you type will go as the input.
The argument of the function is the optional message string. A string given in the bracket will be
displayed while it wait for the input See the following examples
>>> a=raw_input()
You can see that when this statement is executed, the system is waiting for an input. Type anything on
the screen and press enter
It is important that anything you type will go as a single string in this case. Now see what happened
when a message string is also includes in the function.
>>> a=raw_input('type something and press enter key: ')
type something and press enter key :
You can see that it is echoing the message string while waiting for your input
1.12.2.2.2 input()Statement
Python.2x: To input different values either strings or numerals at the same time we can use input()
statement.
>>> a=input()
10
>>> print a
10
>>> a,b=input('Enter two values separated by comma: ')
Enter two values separated by comma: 2,3
>>> print a,b ,a+b
235
>>>
Now it is time for shifting to file mode of executing programs. So try some small programs and
execute it.
Pyton 3.x: input() in python 3.x has the same functionality as raw_input() in python 2.x.
62
>>>a=raw_input() >>>a=raw_input()
2 error
>>>b=raw_input() >>>b=raw_input()
3 error
>>>c=a+b >>>c=a+b # there is no #raw_input() function
>>>print(c) in python #3.x
23 #entered data is #considered as string
input() input()
>>>a=input() >>>a=input()
2 2
>>>b=input() >>>b=input()
3 3
>>>c=a+b >>>c=a+b
>>>print(c) >>>print(c)
5 23 #entered data is considered as string
Therefore for entering data for the purpose of
arithmetic operation following sysntax is
operated
# For integer numbers
>>>a=int(input())
2
>>>b=int(input())
3
>>>c=a+b
>>>print(c)
5
# For floating numbers
>>>a=float(input())
2.33
>>>b=int(input())
3.33
>>>c=a+b
>>>print(c)
5.66
63
>>> c=a+b
print(c)
5
64
Floating number b=float(input)
Complex number c=complex(input)
string d=input()
Note: Unless it is mentioned as int/float/complex, the ‘input()’ take the data as string. This issue
can be solved using eval function. Here instead of string, the datas are taken as datas. Also
multiple inputs can be taken using eval function
eval function
e=eval(input())
a,b,c=eval(input())
Program-2: Write a program to find the sum of 4 numbers using input statement (python 3.x)
Script file
Script file
Program_2.py
1 a=int(input('Enter the first number:'))
2 b=int(input('Enter the second number:'))
3 c=int(input('Enter the third number:'))
4 d=int(input('Enter the forth number:'))
5 sum=a+b+c+d
6 print('sum=',sum)
Output
IDLE Shell 3.10.4
>> Enter the first number:5
> Enter the second number:7
Enter the third number:2
Enter the forth number:3
sum= 17
Program-3: Find the mean of three floating numbers using input statement (python 3.x)
Script file
Program_3.py
1 a=float(input('Enter the first number:'))
2 b=float(input('Enter the second number:'))
3 c=float(input('Enter the third number:'))
4 mean=(a+b+c)/3
5 print('mean=',mean)
Output
IDLE Shell 3.10.4
>> Enter the first number:4.0
> Enter the second number:5.0
Enter the third number:6.0
mean= 5.0
Program-4: Write a program to add two floating numbers using input statement (python 3.x)
65
Script file
Program_4.py
1 a=float(input('Enter the first number:'))
2 b=float(input('Enter the second number:'))
3 sum=a+b
4 print('sum=',sum)
Output
IDLE Shell 3.10.4
>> Enter the first number:2.55
> Enter the second number:3.45
sum= 6.0
Program-5: Write a program to add two complex numbers using input statement (python 3.x)
Script file
Program_5.py
1 a=complex(input('Enter the first number:'))
2 b=complex(input('Enter the second number:'))
3 sum=a+b
4 print('sum=',sum)
Output
IDLE Shell 3.10.4
>>> Enter the first number:3+4j
Enter the second number:2+5j
sum= (5+9j)
Program-6: Using eval function and input statement, add three numbers (python 3.x)
Script file
Program_6.py
1 a=eval(input('Enter the first number:'))
2 b=eval(input('Enter the second number:'))
3 c=eval(input('Enter the third number:'))
4 sum=a+b+c
5 print('sum=',sum)
Output
IDLE Shell 3.10.4
>>> Enter the first number:3
Enter the second number:5.5
Enter the third number:2
sum= 10.5
Script file
66
output
Enter three numbers(separated using comma):2,5.5,3
d=10.5
Script file
Program_7.py
1 a,b,c=eval(input('Enter three numbers separated by comma:'))
2 sum=a+b+c
3 print('sum=',sum)
Output
IDLE Shell 3.10.4
>>> Enter three numbers separated by comma:2,5.5,3
sum= 10.5
Note: Here you can enter data without specifying whether it is int, float or complex.
Script file
Program_7.py
1 a,b,c= (input('Enter three numbers separated by space:')).split()
2 print(a+b+c)
Output
IDLE Shell 3.10.4
>>> Enter three numbers separated by space:2 3 4
234
Script file
Program_7.py
1 a,b,c = list(map(int, input("Enter three numbers separated by space:
2 ").split()))
print(a+b+c)
Output
IDLE Shell 3.10.4
>>> Enter three numbers separated by space:2 3 4
9
Script file
Program_7.py
1 a,b,c = list(map(float, input("Enter three numbers separated by space:
2 ").split()))
print(a+b+c)
Output
IDLE Shell 3.10.4
>>> Enter three numbers separated by space:2.2 3.55 4.723
10.473
67
1.13 Control Structure/ Control Flow
Control structure deals with the flow of execution of different statements in a program or it deals with
the order in which the program’s cod executes.
The control flow of a python program is regulated by conditional statements, loops and function calls.
Python has three types of control structures.
1.13.1 Sequential
Sequential statements are a set of statements whose execution process happens in a sequence. By
default, basic flow is statements execute one after the other in sequential way. Hence this fundamental
type of control structure is known as sequential structure. Eg.
>>>a,b=20,10
>>>c=a+b
>>>print(c)
In the above program, the first line executes first, second line second and so on in a sequential way. The
problem with sequential statement is that if the logic has broken in any one of the line, then the complete
source code execution will break.
But sometimes we need to modify this. There are two ways of modifying this. Hence two more control
structures are here. They are Selection (Conditional) and Repetitive (Iterative/ looping) structures.
This is used to execute a set of statements only if some condition is satisfied or not satisfied (not for
both). This is implemented with the help of a logical Expressions. Hence, We will briefly discuss what
a logical expression is.
Eg.
68
>>>a,b=10,20
>>> a>b
False
>>>a<b
True
Now you can combine two or more logical expressions using logical operators to get logical
expression.
>>> 2 > 3 or 10 > 5
True
>>> 2 > 3 and 10 > 5
False
>>> 3>2 and 10 > 5
True
When a set or block of statement (if block) is to be executed while some condition is true, the if
statement can be used
The syntax of using if statement is
if logical expression:
statements to be executed
while the expression (condition)
is true (if block) as an indented block
(indentation determines the if block)
Indentation in python
In Python, indentation refers to the spaces or tabs at the beginning of a line of code that determine the
grouping of statements. Unlike many other programming languages that use braces {} or keywords like
begin and end to define blocks of code, Python uses indentation for this purpose. The importance of
indentation in Python can be summarized as follows:
Readability: Indentation enhances the readability of Python code. The visual structure provided by
indentation makes it easier for programmers to understand the logical flow and hierarchy of the code.
Consistent and well-organized indentation improves code readability for both the original author and
others who may read or maintain the code.
69
Code Structure: Indentation is crucial for defining the structure of the code, especially in control flow
statements (e.g., loops and conditional statements) and function definitions. It visually represents the
scope of statements and the relationships between different parts of the code.
Enforcement of Block Structure: In Python, indentation is not just a matter of style; it is a syntactical
requirement. The interpreter uses indentation to determine the beginning and end of blocks of code.
Incorrect indentation can lead to syntax errors or, more critically, result in the misinterpretation of the
code logic.
No Need for Explicit Braces: Python's use of indentation eliminates the need for explicit braces or
keywords to denote code blocks. This results in cleaner, more concise code. However, it also means
that proper indentation is essential for the code to be correctly interpreted.
Consistency: Indentation promotes coding consistency across projects and among developers. Since
Python relies on indentation for code structure, adherence to a consistent indentation style is crucial for
maintaining code uniformity and collaboration.
Visual Clarity: Proper indentation provides a visual indication of the nesting level of code blocks. This
makes it easy to identify the relationships between different parts of the code, helping programmers
quickly grasp the overall structure.
Eg:
# Incorrect indentation
if True:
print ("This line is not properly indented")
# Correct indentation
if True:
print ("This line is properly indented")
Ans:
Condition is x>10
You can see that the statement inside the ‘if block’ is executed only when the number is greater than
10
Points to notice:
70
Script file
Program_8.py
1 x=int(input('Enter a number:'))
2 if x>=10:
3 print('Number is greater than 10')
4 print('Program finished')
Output
IDLE Shell 3.10.4
>> Enter a number:9
> Program finished
Enter a number:13
>> Number is greater than 10
> Program finished
Script file
Program_9.py
1 x=int(input('Enter a number:'))
2 if x>0:
3 print('Number is positive')
4 print('Program finished')
Output
IDLE Shell 3.10.4
>> Enter a number:11
> Number is greater than 10
Program finished
Enter a number:3
>> Number is greater than 10
> Program finished
if logical expression:
statements to be executed
while the expression (condition)
is true (if block) as an indented block
else:
statements to be executed
while the expression (condition)
is false (else block) as an indented block
71
program-10: Modify program-4 to check the given number is greater than or less than 10 using
if..else statement
Script file
Program_10.py
1 x=int(input('Enter a number:'))
2 if x>=10:
3 print('Number is greater than 10')
4 else:
5 print('Number is less than 10')
6 print('Program finished')
Output
IDLE Shell 3.10.4
>> Enter a number:11
> Number is greater than 10
Program finished
Enter a number:4
>> Number is less than 10
> Program finished
program-11: Write a program to find whether the given number is even or odd using if…else
statement
Script file
Program_11.py
1 x=int(input('Enter a number:'))
2 if x%2==0:
3 print('Number is even')
4 else:
5 print('Number is odd')
6 print('Program finished')
Output
IDLE Shell 3.10.4
>> Enter a number:10
> Number is even
Program finished
Enter a number:9
>> Number is odd
> Program finished
program-12: Write a program to find the largest among three numbers using if..else statement
Script file
Program_12.py
1 a=int(input('Enter the 1st number,a:'))
2 b=int(input('Enter the 2nd number,b:'))
72
3 c=int(input('Enter the 3rd number,c:'))
4 if a>b:
5 if a>c:
6 l=a
else:
l=c
else:
if b>c:
l=b
else:
l=c
print('largest number=',l)
Output
IDLE Shell 3.10.4
>> Enter the 1st number,a:10
> Enter the 2nd number,b:20
Enter the 3rd number,c:30
largest number= 30
73
1.13.2.4 if…elif…elif… ….else
The syntax is
if logical expression1:
block 1
elif logical expression2:
block 2
elif logical expression3:
block 3
…….
…….
…….
else:
block n
Here the test starts from logical exp1. If this is true block 1 statements will be executed. If it is false it
will check for the second condition (logical exp2)and if this is true block 2 statements will be executed
an so on. If all test are false it will execute the statements in the else block (block n).
program-13: Write a program to find the grade of a student for a given using if..elif..else statement
74
Mark Grade
>=90 A+
>=80 A
>=70 B
>=60 C
>=50 D
>=40 E
<40 Failed
Script file
Program_13.py
1 mark=int(input('Enter the mark:'))
2 if mark>=90:
3 print('Grade=A+')
4 elif mark>=80:
5 print('Grade=A')
6 elif mark>=70:
7 print('Grade=B')
8 elif mark>=60:
9 print('Grade=C')
10 elif mark>=50:
11 print('Grade=D')
12 elif mark>=40:
13 print('Grade=E')
14 else:
15 print('Grade=Failed')
Output
IDLE Shell 3.10.4
>>> Enter the mark:71
Grade=B
Program-14: Write a program to find the region of electromagnetic spectrum if given a wavelength
Wavelength(nm) EM region
>780 IR
>620 Red
>585 Orange
>490 Green
>440 Blue
>420 Indigo
>350 Violet
75
<350 UV
Script file
Program_14.py
1 wavelength=int(input('Enter a wavelength:'))
2 if wavelength>=780:
3 print('EM region=IR')
4 elif wavelength >=620:
5 print('EM region=Red')
6 elif wavelength >=585:
7 print('EM region=Orange')
8 elif wavelength >=490:
9 print('EM region=Green')
10 elif wavelength >=440:
11 print('EM region=Blue')
12 elif wavelength >=420:
13 print('EM region=Indigo')
14 elif wavelength >=350:
15 print('EM region=Violet')
16 else:
17 print('EM region=UV')
Output
IDLE Shell 3.10.4
>>> Enter a wavelength:330
EM region=UV
Next we will see another type of control structure in which a set of statement (block) is executed for a
definite number of time. There are two types of loops in python.
(i) while loop
(ii) for loop
76
1.13.3.1 while loop
The while loop (or statement) allows you to repeatedly execute a block of statements (indented block)
as long as a condition is true. A while statement is an example of what is called a looping statement. A
while statement can have an optional else clause . The syntax of a while loop is:
while logical exp:
indented block to be
executed while
the condition is true
program 15: Write a program to print numbers from 1 to 10 using while loop
Script file
i=1 # instead of i any symbolic letter can be used
while i<=10: # :(colon) is must after logical expression
print(i)
i=i+1
output:
1
2
3
4
5
6
7
8
9
10
Note: The loop will repeat until the condition become False
-Value of i is initially set to 1 (first
line)
-The conditions is set such that i can
have values less than or equal to 10
(i<=10)
-In the first loop, value of i is 1. At
line-2 logical condition (while i<=10)
will check whether the value of i is
less than or equal to 10. If yes,
logical conditions is True, indented
statements will execute (line-3&4). If
no, logical condition is False,
indented statmement will not execute or
loop will stop.
-If the logical condition is True, it
will go to line-3, and print i, i=1 in
the first loop. At line-4, value of i
is incremented by one, i is 2 now in
the first loop. Loop return back to
line-2.
-In the second loop,at line-2 condition
will be checked again and the process
will repeat.
77
-After many increment of i, value of i
become 11. At line-2, now the condition
is False. That is, i is now greater
than 10. So the loop will stop
Script file
Program_15.py
1 i=1
2 while i<=10:
3 print(i)
4 i=i+1
Output
IDLE Shell 3.10.4
>> 1
> 2
3
4
5
6
7
8
9
10
program 16: Write a program to print numbers from 0 to n using while loop (any given number)
Script file
Program_16.py
1 n=int(input('Enter a number,n='))
2 i=0
3 while i<=n:
4 print(i)
5 i=i+1
Output
IDLE Shell 3.10.4
>> Enter a number,n=5
> 0
1
2
3
4
5
78
2 2+1=i+previous sum=3 At every step, to get sum integer is
added to the sum of the previous
3 3+3=i+previous sum=6
stage.
4 4+6=i+previous sum=10 Eg.when i=4, previous sum is 6.
Therefore new sum is current
5 5+10=i+previous sum=15
i+previous sum
6 6+15=i+previous sum=21 So the general equation is
sum=sum+i
7 7+21=i+previous sum=28
Here initially, before the first loop,
8 8+28=i+previous sum=36 previous sum is set to zero
9 9+36=i+previous sum=45
10 10+45=i+previous sum=55
Script file
Program_17.py
1 i=1
2 sum=0
3 while i<=10:
4 sum=sum+i
5 i=i+1
6 print(‘sum=’,sum)
Output
IDLE Shell 3.10.4
>> sum= 55
>
program 18: Write a program to find the sum of integers from 1 to 10, display integers 1 to 10 in one
column and corresponding sum till that number in another column (modify program no.17)
Script file
Program_18.py
1 i=1
2 sum=0
3 while i<=10:
4 sum=sum+i
5 print(‘i=’,i,’sum=’,sum)
6 i=i+1
7 print(‘sum=’,sum)
Output
IDLE Shell 3.10.4
>> i= 1 sum= 1
> i= 2 sum= 3
i= 3 sum= 6
i= 4 sum= 10
i= 5 sum= 15
i= 6 sum= 21
i= 7 sum= 28
i= 8 sum= 36
79
i= 9 sum= 45
i= 10 sum= 55
sum= 55
Script file
Program_19.py
1 n=int(input(‘Enter a number:’))
2 i=1
3 sum=0
4 while i<=n:
5 sum=sum+i
6 i=i+1
7 print(‘sum=’,sum)
Output
IDLE Shell 3.10.4
>> Enter a number:5
> sum= 15
Enter a number:20
>> sum= 210
>
Enter a number:100
sum= 5050
>>
>
program 20: Write a program to find the sum of multiples of 5 from 0 t0 100
Script file
Program_20.py
1 i=0
2 sum=0
3 while i<=100:
4 sum=sum+i
5 i=i+5
6 print(sum)
7 print(‘sum=’,sum)
Output
IDLE Shell 3.10.4
>> 0
> 5
15
30
50
75
105
140
180
80
225
275
330
390
455
525
600
680
765
855
950
1050
sum=1050
program 22: Write a program to print the multiplication table of any given number
Script file
Program_22.py
1 n=int(input('Enter a number:'))
2 i=1
3 while i<=10:
4 print(i,'x', n, '=',i*n)
5 i=i+1
Output
IDLE Shell 3.10.4
>> Enter a number:5
> 1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
4 x 5 = 20
81
5 x 5 = 25
6 x 5 = 30
7 x 5 = 35
8 x 5 = 40
9 x 5 = 45
10 x 5 = 50
The for...in statement is another looping statement which iterates over a sequence (string/list/tuple) of
objects i.e. Go through each item in a sequence. We have already seen what a sequence is. Hence the
loop will be repeated as many as the number of elements in the sequence
The syntax is
for variable in sequence:
The statements in the for domain
or block is executed exactly as
the number of elements present
in the sequence.
During the first iteration the variable is assigned with the first element, during second
iteration the variable is assigned with second element and so on till the last element.
program 23: Print ‘python’ using for loop (Example-1)
Script file
Program_23.py
1 for i in 'python':
2 print(i)
Output
IDLE Shell 3.10.4
>> p
> y
t
h
o
n
82
car
(-2+3j)
Range function
The syntax for using range function is
83
range([start,] stop[, step])
This will return a list containing an arithmetic progression of integers starting from start and
incremented by step until stop (not including stop). Here start, stop and step are valid integers.
If only one argument is given, it will be taken as stop and the start = 0 and step =1
if only two arguments are given, these will be taken as start and stop while step =1
For example range(n1,n2,n3) will give a list containing n1, n1+n3, n1+2n3 ..upto all values in this
series up to but excluding n2.
Some examples are given below
>>>range(10)
[0,1,2,3,4,5,6,7,8,9]
>>>range(11)
[0,1,2,3,4,5,6,7,8,9,10]
>>>range(1,11)
[1,2,3,4,5,6,7,8,9,10]
>>>range(1,11,2)
[1,3,5,7,9]
>>>range(0,11,2)
[0,2,4,6,8,10]
>>>range(0,11,5)
[0,5,10]
Python Shell 2.7.1
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(11)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(1,11,2)
[1, 3, 5, 7, 9]
>>> range(1,11,3)
[1, 4, 7, 10]
>>> range(0,11,2)
[0, 2, 4, 6, 8, 10]
>>> range(0,11,5)
[0, 5, 10]
>>> range(-25,25,10)
[-25, -15, -5, 5, 15]
84
Script file
Program_28.py
1 for x in range(1,11):
2 print(x)
Output
IDLE Shell 3.10.4
>> 1
> 2
3
4
5
6
7
8
9
10
85
4 print('sum=',sum)
Output
IDLE Shell 3.10.4
>> sum= 55
>
program 31: Write a program to print sum of integers from 1 to 10, print number and sum in every
step and store all the result as a list
Script file
Program_31.py
1 sum=0
2 x=[]
3 y=[]
4 for i in range(1,11):
5 sum=sum+i
6 x.append(sum)
7 y.append(i)
8 print('sum=',sum)
9 print(‘x=’,x)
10 print(‘y=’,y)
Output
IDLE Shell 3.10.4
>> 00
11
23
36
4 10
5 15
6 21
7 28
8 36
9 45
10 55
x= [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
y= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
86
5 x 5 = 25
6 x 5 = 30
7 x 5 = 35
8 x 5 = 40
9 x 5 = 45
10 x 5 = 50
program 33: Write a program to print the following pattern using for loop and while loop
*
**
***
****
*****
for loop
Script file
Program_33.py
1 for i in range(1,6):
2 print('*'*i)
Output
IDLE Shell 3.10.4
>> *
> **
***
****
*****
while loop
Script file
Program_33.py
1 i=1
2 while i<=5:
print('*'*i)
i=i+1
Output
IDLE Shell 3.10.4
>> *
> **
***
****
*****
program 34: Write a program to print the following using for loop and while loop
2
4
8
16
32
64
128
87
256
512
1024
while loop
Script file
Program_34.py
1 i=1
2 while i<=10:
3 print(2**i)
4 i=i+1
Output
IDLE Shell 3.10.4
>> 2
> 4
8
16
32
64
128
256
512
1024
for loop
Script file
Program_34.py
1 for c in range(1,11):
2 print(2**c)
Output
IDLE Shell 3.10.4
>>> 2
4
8
16
32
64
128
256
512
1024
program 35: write a program to find the factorial of 5 (5!) using for loop
Ans: Factorial of 5 is given by 5!=1 x 2 x 3 x 4 x 5=120. The multiplication process can be written as
follow
1 i
2 x 1=2 i x previous factorial (i x 1)
3 x 2 x 1=6 i x previous factorial (i x 2)
4 x 3 x 2 x 1=24 i x previous factorial (i x 6)
5 x 4 x 3 x 2 x 1=120 i x previous factorial (i x 24)
fact=i * fact
for loop
88
Script file
Program_35.py
1 fact=1
2 for i in range(1,6):
3 fact=fact*i
4 print(fact)
Output
IDLE Shell 3.10.4
>> 120
>
program 36: write a program to find the factorial of any given number using for loop
while loop
Script file
Program_36.py
1 n=int(input('Enter a number:'))
2 fact=1
3 for i in range(1,n+1):
4 fact=fact*i
print(fact)
Output
IDLE Shell 3.10.4
>> Enter a number:10
> 3628800
We can use the break statement to terminate a loop, if some condition is met. The continue statement
isused to skip the rest of the block and go to the beginning again. Both are demonstrated in the following
example programs.
program 37: using break, break the printing of 1 to 10 at 5
Script file
Program_37.py
1 for c in range(1,11):
2 if c==5:
3 break
4 print(c)
Output
IDLE Shell 3.10.4
>> 1
> 2
3
4
89
Script file
Program_38.py
1 for c in range(1,11):
2 if c==5:
3 continue
4 print(c)
Output
IDLE Shell 3.10.4
>> 1
> 2
3
4
6
7
8
9
10
Script file
Program_37.py
1 days=['Sunday','Monday','Tuesday','Wednessday','Thursday','Friday','s
2 aturday']
3 for i,d in enumerate(days):
4 print(i,d)
Output
IDLE Shell 3.10.4
>> 0 Sunday
> 1 Monday
2 Tuesday
3 Wednessday
4 Thursday
5 Friday
6 saturday
Script file
Program_37.py
1 a=range(1,10)
2 b=range(11,20)
3 for i,j in zip(a,b):
4 sum=i+j
print(sum)
Output
IDLE Shell 3.10.4
>> 12
> 14
16
18
90
20
22
24
26
28
1.14 Functions
Functions are reusable pieces of programs which can be tested separately. They allow you to give a
name to a block of statements and you can run that block using that name anywhere in your program
and any number of times. This is known as calling the function. We have already used many built-in
functions such as the len, max, type, range etc. (You can see the list of built-in functions by entering
dir(__builtins__) in python prompt. Usage of each function can be obtained by the function help() with
function name as argument as shown below.
IDLE Shell 3.10.4
>>> import math as m
>>> help(m)
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
-----------------------------------------------------
-----------------------------------------------------
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
(built-in)
91
We can define our own functions and this is known as user defined functions. Functions are defined
using the def keyword. This is followed by an identifier name for the function followed by a pair of
parentheses which may enclose some names of variables and the line ends with a colon. Next follows
the block of statements that are part of this function. Finally, there may be an optional keyword, return
, followed by name of variables whose value is to be retuned (given back) to the calling program in the
indented block (function block).
92
25 print('Address')
26 print('state')
27 print('country')
28 x1=15
29 x2=14
30 x3=13
31 x4=12
32 x5=11
33 mean=(x1+x2+x3+x4+x5)/5
34 print(mean)
35 print('Name')
36 print('Address')
37 print('state')
38 print('country')
In the above program, the first four lines are repeated twice later. The first four lines can be defined as
a function by choosing a suitable function name (eg. home()). Then where ever the same lines repeat,
then these lines can be replaced by function name home (). This single line function name will do exactly
what the four lines are expected to do.
Similarly, line 5-9 are denoting the addition of three variables a,b and c. The same three number addition
process repeats at line 19-23. Here the lines 5-9 can be defined as a function by giving any function
name say add3(a,b,c). Here the function name consists of three arguments since the function consists
of three variables. Once the function is defined, the addition of any three numbers can be performed by
calling the function by assigning values to the arguments as shown below. Similarly for line 12-18
which is for finding the mean of any 5 numbers.
The above program can be written using functions as follows
Script file
Program_39.py
1 def home():
2 print('Name')
3 print('Address')
4 print('state')
5 print('country')
6 home()
7 def add3(a,b,c):
8 d=a+b+c
9 return d
10 print(add3(1,2,3))
11 i=1
12 print('Hello')
13 def mean5(x1,x2,x3,x4,x5):
14 m=(x1+x2+x3+x4+x5)/5
15 return m
93
16 print(mean5(5,4,3,2,1))
17 print(add3(5,6,7)) #line 19-23 is replaced by function add3(a,b,c)
18 home() #line 24-27 is replaced by function home()
19 print(mean5(15,14,13,12,11)) #line 28-34 is replaced by function
20 #mean5(a,b,c,d,e)
21 home() #line 35-38 is replaced by function home()
program 41: Function example-2: Define a function to find the sum of two numbers
Script file
Program_41.py
1 def add2(a,b):
2 c=a+b
3 return c
4 print(add2(2,4))
5 print(add2(30,10))
6 print(add2(100,150))
Output
IDLE Shell 3.10.4
>>> 6
40
250
program 42: Function example-3: Define a function to find the sum of three numbers
Script file
Program_42.py
1 def sum(x,y,z):
94
2 w=x+y+z
3 return w
4 print(sum(2,4,8))
5 print(sum(30,10,12))
6 print(sum(100,150,623))
Output
IDLE Shell 3.10.4
>>> 14
52
873
program 43: Function example-4: Define a function to find the largest of three numbers
Script file
Program_43.py
1 def largest(a,b,c):
2 if a>b:
3 if a>c:
4 l=a
5 else:
6 l=c
7 else:
8 if b>c:
9 l=b
10 else:
11 l=c
12 return l
13 print(largest(2,5,1))
14 print(largest(7,-1,2))
15 print(largest(20,-500,100))
16 print(largest(-50,-20,-1))
Output
IDLE Shell 3.10.4
>>> 5
7
100
-1
95
Output
IDLE Shell 3.10.4
>>> 24
240000
2400000000
-600
program 46: Define a function to find the value of the following trigonometric function
𝑦 = 𝑠𝑖𝑛 (𝜃) + 𝑐𝑜𝑠 (𝜃)
Script file
Program_46.py
1 from math import*
2 def trig(theta):
3 y=sin(theta/57.3)**2+cos(theta/57.3)**2
4 return y
5 print(trig(50))
6 print(trig(22.4))
7 print(trig(90))
Output
IDLE Shell 3.10.4
>>> 1.0
1.0
0.9999999999999999
program 47: Define a function to find the root of the quadratic equation
𝑎𝑥 + 𝑏𝑥 + 𝑐 = 0
Ans: The root of the quadratic equation is 𝑥 = −𝑏 ± √𝑏 − 4𝑎𝑐
Eg: (a) 2x2 – 5x + 3 = 0 where a=2,b=-5 and c=3 and the solution are x=3/2 and 1
(b) x2 +4x + 4 = 0 where a=1,b=4 and c=4 and the solution are x=-2 and -2
(c) 2x2 -14x + 24 = 0 where a=2,b=-14 and c=24 and the solution are x=4 and 3
96
Script file
Program_47.py
1 from cmath import*
2 def quad(a,b,c):
3 y1=(-b+sqrt(b**2-4*a*c))/(2*a)
4 y2=(-b-sqrt(b**2-4*a*c))/(2*a)
5 return y1,y2
6 print(quad(2,-5,3))
7 print(quad(1,4,4))
print(quad(2,-14,24))
Output
IDLE Shell 3.10.4
>>> ((1.5+0j), (1+0j))
((-2+0j), (-2+0j))
((4+0j), (3+0j))
program 48: Define a function to print the multiplication table of any number. By calling the function
print the multiplication table of 2,10 and 30
Script file
Program_48.py
1 def multitable(n):
2 for i in range(1,11):
3 x=print(i,'x',n,'=',n*i)
4 return(x)
5 print(multitable(2))
6 print(multitable(20))
7 print(multitable(30))
Output
IDLE Shell 3.10.4
>>> 1 x 2 = 2
2x2=4
3x2=6
4x2=8
5 x 2 = 10
6 x 2 = 12
7 x 2 = 14
8 x 2 = 16
9 x 2 = 18
10 x 2 = 20
1 x 20 = 20
2 x 20 = 40
3 x 20 = 60
4 x 20 = 80
5 x 20 = 100
6 x 20 = 120
7 x 20 = 140
8 x 20 = 160
97
9 x 20 = 180
10 x 20 = 200
1 x 30 = 30
2 x 30 = 60
3 x 30 = 90
4 x 30 = 120
5 x 30 = 150
6 x 30 = 180
7 x 30 = 210
8 x 30 = 240
9 x 30 = 270
10 x 30 = 300
program 49: Define a function to print multiples of x from n to m where x,n,m are all integers (Eg.
Multiplex of 5 from 10 to 50)
Script file
Program_49.py
1 def multi(x,n,m):
2 for i in range(n,m+1,x):
3 y=print(i)
4 return(y)
5 print(multi(5,10,50))
6 print(multi(2,0,20))
Output
IDLE Shell 3.10.4
>>> 10
15
20
25
30
35
40
45
50
None
0
2
4
6
8
10
12
14
16
18
20
None
98
1.15 Local Variables
When you declare variables inside a function definition, they are not related in any way to other
variables with the same names used outside the function i.e. variable names are local to the function.
This is called the scope of the variable. All variables have the scope of the block they are declared in
starting from the point of definition of the name. This can be explained by a simple program The same
variable is modified outside the function. You can see that it is not affected for the variable with the
same name in the function.
Program-50. Example of local variable
Script file
Program_50.py
1 def func():
2 x = 2
3 x = 10
4 func()
5 print(x)
Output
IDLE Shell 3.10.4
>>> 10
Note: In this program x have two values, x=2 and x=10. X=2 is inside the function and x=10 outside
the function. Since x=2 is local, its value is valid only inside the function.
99
1.17 Modules
You have seen how you can reuse code in your program by defining functions once. What if you wanted
to reuse a number of functions in other programs that you write? As you might have guessed, the answer
is modules. A module is basically a file containing all your functions and variables that you have
defined. To reuse the module in other programs, the filename of the module must have a .py extension.
A module can be imported by another program to make use of its functionality. This is how we can use
the Python standard library as well. First, we will see how to use the standard library modules. An
essential standard library module for a science student is the math module in which all mathematical
routines are defined.
Modules in Python are files containing Python code that define functions, classes, and variables that
can be reused in other Python scripts. Modules help organize and structure code, making it more
maintainable and reusable.
Before going to the details of math module we will discuss the different methods of using or importing
it in our programs. Basically, there are four methods for this.
The simplest methods of importing a module is using the syntax import module_name (.py can be
omitted here) Hence to use math module, in the beginning of the program there must be the import
statement as import math once the math module is imported you can use the functions or variables in
the math module using a the module name and function/variable name connected by a . (dot).
For example to use the sin() or cos() function or the pi value you have to use as math.sin(),
math.cos() and math.pi respectively.
Program-52. Example of import module
IDLE Shell 3.10.4
>>> Import math
>>> math.sin(30/57.3)
0.49996660034157375 #1r= = 57.3
>>>
math.sin(60/57.3)
0.8659868350340963
>>>
math.sin(90/57.3)
0.9999999933069259
>>>
math.sin(0)
0.0
>>>
math.cos(45/57.3)
0.707147685608313
>>>
100
math.cos(30/57.3)
>>> 0.8660446862275001
math.cos(0)
>>> 1.0
math.tan(45/57.3)
0.9998843081699127
Program-53. Find the inverse of the following values (a) sin-1 (0.5), (b) sin-1 (0), (c) cos-1 (0.707), (d)
tan-1(1) and (e) cos-1 (1)
IDLE Shell 3.10.4
>>> Import math
>>> math.asin(0.5)*57.3
30.002209841782527
>>> math.asin(0)*57.3
0.0
>>> math.acos(0.707)*57.3
45.01196706280531
>>> math.atan(1)*57.3
45.00331476267378
>>> math.acos(1)*57.3
0.0
So, you might have noticed that in this type of import, you have to prefix the module name with every
definition. If the module name is very large the typing this everywhere will be very difficult. Hence, we
can use an alias. For this we can import a module with another name (which may be convenient to
handle)
Program-55. Example of import module as alias
IDLE Shell 3.10.4
>>> import math as m
>>> m.sin(30/57.3)
0.49996660034157375
>>> m.cos(30/57.3)
101
0.8660446862275001
>>> m.pi
3.141592653589793
Here you can see that the name math is changed to m while importing
Another method to import a module by avoiding the use of module name with every definition is using
the syntax from module import *. In this method there is no need to prefix the module name.
Program-56. Example of from module import*
IDLE Shell 3.10.4
>>> from math import*
>>> sin(60/57.3)
0.8659868350340963
>>> cos(60/57.3)
0.5000667970857781
>>> pi
3.141592653589793
The main disadvantage of using this method is that you cannot use two definitions with same name
even if they are in different modules. One of them will be overwritten.
The fourth method is to import selected definitions only using the syntax from module import
definitions.
Program-57. Example of from module import selected definitions
IDLE Shell 3.10.4
>>> from math import sin,pi
>>> sin(10/57.3)
0.17363551756345838
>>> pi
3.141592653589793
102
>>> import math
>>> help(math)
This will give a listing of different functions in math module. A part of the listing is given below
Help on built-in module math:
NAME
math
FILE
(built-in)
DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.
FUNCTIONS
acos(...)
acos(x)
Return the arc cosine (measured in radians) of x.
acosh(...)
acosh(x)
Return the hyperbolic arc cosine (measured in radians)
103
12 c=a+b
13 return c
14 def sum3(a,b,c):
d=a+b+c
15
return d
16 def hello():
17 print('Welcome to python')
18 print('Good morning')
save this as mymodule.py and see how the functions in the module can be used.
Output
IDLE Shell 3.10.4
>>> from mymodule import*
>>> largest(10,2,3)
10
>>> add2(5,7)
12
>>> sum3(10,4,20)
34
>>> hello()
Welcome to python
Good morning
Program-59. Create a user defined module to perform the following geometric operations
(a) area-triangle
-square
-rectangle
-circle
-cube
-cylinder
-sphere
(a) volume-cube
-cylinder
-sphere
Area Volume
Triangle=1/2 (b x h) cube=a3
square=a2 cylinder=Πr2h
rectangle=a x b sphere=4/3 Πr3
circle=Πr2
cube=6a2
cylinder=2 Πr2 + 2Πrh
sphere=4 Πr2
Script file
104
geometry.py
1 from math import*
2 def triangleA(b,h):
3 area=(1/2)*(b*h)
4 return(area)
5 def squareA(a):
6 area=a*a
7 return(a)
8 def rectangleA(a,b):
9 area=a*b
10 return(area)
11 def circleA(r):
12 area=pi*r*r
13 return(a)
14 def cubeA(a):
15 area=6*a**2
16 return(area)
17 def sphereA(r):
18 area=4*pi*r*r
19 return(area)
20 def cylinderA(r,h):
21 area=2*pi*r*r+2*pi*r*h
22 return(area)
23 def cubeV(a):
24 volume=a**3
25 return(volume)
26 def cylinderV(r,h):
27 volume=pi*r*r*h
28 return(volume)
29 def sphereV(r):
30 volume=(4/3)*pi*r**3
31 return(volume)
save this as geometry.py and see how the functions in the module can be used.
Output
IDLE Shell 3.10.4
>>> import geometry as g
>>> g.cubeA(4)
96
g.cubeV(4)
>>> 64
g.rectangleA(2,3)
6
>>> g.sphereA(5)
314.1592653589793
Program-60. Create a user defined module to perform all the arithmetic operations in python
Script file
105
arithmetic.py
1 def add2(a,b):
2 c=a+b
3 return c
4 def add3(a,b,c):
5 d=a+b+c
6 return d
7 def sub(a,b):
8 c=a-b
9 return c
10 def mul(a,b):
11 c=a*b
12 return c
13 def div(a,b):
14 c=a/b
15 return c
16 def flo(a,b):
17 c=a//b
18 return c
19 def mod(a,b):
20 c=a%b
21 return c
22 def ex(a,b):
23 c=a**b
24 return c
save this as arithmetic.py and see how the functions in the module can be used.
Output
IDLE Shell 3.10.4
>>> from arithmetic import*
>>> add3(5,8,1)
14
>>> mod(5,2)
1
>>> ex(3,2)
9
>>> div(10,2)
5.0
1.19 Data files (File input and output)(Read from a file and Write to a file)
Python can handle data files. Data can be written to an output file and data can be read from an input
file. He re we will discuss the basic techniques to handle a data file. In order to use a data file we have
to open a file. The syntax for opening a file is
var = open(filename, mode)
The variable var will act as the file object corresponding to the file. So a file is opened using open
function. For this function two arguments are needed. First one is a string containing the file name. File
106
name has two parts, a file name and an extension (eg. myfile.txt). Here txt is the extension of the file
type. Depending on the file type, the extension can be .txt (text file), .dat (notepad), .doc (ms word),
.csv (ms excel), .xlsx (ms excel). The second is the mode of operation. There are three modes of
operation; they are
'w' – This is used to create a new output file. If no file exists with the given name a new file is
created and if a file is already existing the file will be deleted and a new one is created.
'r' – This is to open an existing file as input file for reading data from it. If no file is present with
the name given, an error message will be displayed.
'a' – This is for writing data at the end of an already existing file (appending).
The different file types are shown in figure
Now let us create a new file with name 'sample.dat' and put some data in this
Save a script file with name say program_write.py in some folder with the following lines
Script file
Program_write.py
1 f=open('sample.dat','w') #instead of .dat extension, other
2 #extensions such as .txt or .csv can be
3 #used to create text file or excel file
4 #respectively
5 f.write('The features of python are \n') #\n is for new line
6 f.write('simple and easy to learn \n’)
7 f.write('Free and open source \n’)
8 f.write('Interpreted \n’)
9 f.write('Object oriented’)
10 f.close() #f.close() is must when writing a file
Folder view
107
File view
108
Output
IDLE Shell 3.10.4
>>> The features of python are
Interpreted
Object oriented
You can see that using readline data is taken line by line. Now if you want to read the data again you
have to take the file pointer to the begining of file. This can be done by seek()
>>>f.seek(0)
0
>>>f.readline()
The features of python are
To read the whole data in a single go, use the following line
>>>f.read()
The features of python are
simple and easy to learn
Free and open source
Interpreted
Object oriented
Output
IDLE Shell 3.10.4
>>> f.seek(0)
0
>>> print(f.read())
The features of python are
simple and easy to learn
Free and open source
Interpreted
109
Object oriented
Now let's add some more data to the already existing file (sample.dat) by opening win 'a' mode
Save the following lines in a script file with some name say append.py
Script file
Program_append.py
1 f=open('sample.dat','a')
2 f.write('Welcome to python \n')
3 f.write('Good morning \n')
f.write('This is how appending is used to add more lines')
4
f.close()
5
When you open the data file sample.dat you can see the following
File view
Last three lines are added to the already existing first five lines
110
1.20.1 Write a file using pickle
To open a file named datafile.pck, write the following lines in a script file and save using some name
pickle_write.py
Script file
Pickle_write.py
1 import pickle
2 f=open('datafile.pck','rb')
3 pickle.dump(233,f)
4 pickle.dump(3.2,f)
5 pickle.dump([1,2,3,4,5],f)
6 pickle.dump((5.5,4+3j),f)
f.close()
Folder view
save this as pickle_read.py and see how the functions in the module can be used.
To read the data stored in datafile.pck, write the following lines in a script file and save using some
name say pickle_read.py
Script file
Pickle_write.py
1 import pickle
2 f=open('datafile.pck','wb')
3 print(pickle.load(f))
4 print(pickle.load(f))
5 print(pickle.load(f))
6 print(pickle.load(f))
Output
IDLE Shell 3.10.4
>>> 233
3.2
[1, 2, 3, 4, 5]
(5.5, (4+3j))
111
1.21 Pandas (Not a part of syllabus)
Pandas is a popular open-source Python library used for data manipulation and analysis. It provides
powerful data structures and tools for working with structured data, such as tabular data (e.g., CSV files,
Excel spreadsheets, SQL tables) and time series data. Some of the key features of pandas include:
1. Write a program to find the sum of integers from 0 10 using for loop, print the number and sum
for every number from 0 to 10 and save the result in an excel file named ‘sum’ using pandas
library and plot number vs sum.
Script file
mymodule.py
1 import pandas as pd
2 sum=0
3 data=[]
4 for i in range(0,11):
5 sum=sum+i
6 print(i,sum)
7 raw_data={
8 'i':i,
9 'sum':sum
10 }
11 data.append(raw_data)
12 df = pd.DataFrame(data)
13 # Convert the list of dictionaries to a pandas DataFrame
112
14 file_name = 'sum.xlsx'
15 # Specify the file path where you want to save the Excel file
16 df.to_excel(file_name, index=False)
17 # Save the DataFrame to an Excel file
Output
IDLE Shell 3.10.4
>>> 0 0
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
Excel file view
2. Write a program to load the above excel file named ‘sum’ and plot the i vs sum data
Script file
mymodule.py
1 import pandas as pd
2 import matplotlib.pyplot as plt
3 # Load the Excel file into a pandas DataFrame
4 file_name = 'sum.xlsx'
5 df = pd.read_excel(file_name)
6 # Assuming the DataFrame has columns 'x' and 'y'
7 # Replace 'x' and 'y' with your column names
113
8 x = df['i']
9 y = df['sum']
10 # Plot the data using matplotlib
11 plt.plot(x, y,'r', marker='o', linestyle='-')
12 plt.title('i vs sum')
13 plt.xlabel('i')
14 plt.ylabel('sum')
15 plt.grid(True)
16 plt.show()
Output
IDLE Shell 3.10.4
>>>
3. Write a program to simulate projectile motion and store the generated x,y, vx,vy and t date to
an excel file using pandas module (Better to run the program in spyder (to install:
https://www.spyder-ide.org/ )) [Create a folder and save the program, the program will save
the output data in a file 'projectile.xlsx']
Script file
Program_132.py
1 from pylab import*
2 def f1(t,x,vx): #Define function f1, which is x component of accelaration
3 return(0)
4 def f2(t,y,vy): #Define function f2, which is y component of accelaration
5 return(-9.8)
6 def f3(t,x,vx): #Define function f3, which is x component of velocity
7 return(vx)
8 def f4(t,y,vy): #Define function f4, which is y component of velocity
9 return(vy)
10 U=float(input('Enter initial velocity(m/s),U:')) #Enter U from keyboard
11 theta=float(input('Enter angle of projection:')) #Enter theta from keyboard
12 rtheta=theta/57.3 # To get thera in angle instead of radians
13 h=float(input('Enter time step,h:')) #Enter time step
14
15 x=0 # Set initial value of x
16 y=0 # Set initial value of y
17 t=0 # Set intial value of time
18
114
19 vx=U*cos(rtheta) # x component of initial velocity U
20 vy=U*sin(rtheta) # y component of initial velocity U
21
22 xdata=[] # A null list to store x data obtained from simulation
23 ydata=[] # A null list to store y data obtained from simulation
24 data=[] # A null list where data for excel file will be stored
25
26 print(' t ',' x ',' y ',' vx ',' vy ')
27
28 while y>=0: # Start a while loop (condition is true till object reach ground,y=0)
29 vx=vx+h*f1(t,x,vx) # Euler method to get next vx value, vx=vx+h*ax
30 vy=vy+h*f2(t,y,vy) # Euler method to get next vy value, vx=vx+h*ay
31 x=x+h*f3(t,x,vx) # Euler method to get next x value, x=x+h*vx
32 y=y+h*f4(t,y,vy) # Euler method to get next y value, y=y+h*vy
33 t=t+h # increment time by h
34 xdata.append(x) # store x value in null list named xdata
35 ydata.append(y) # store y value in null list named ydata
36 row_data={
37 't':t,
38 'x':x,
39 'y':y,
40 'vx':vx,
41 'vy':vy
42 }
43 data.append(row_data)
44
45 print('%2.4f %7.4f %7.4f %7.4f %7.4f'%(t,x,y,vx,vy))
46
47 # Convert the list of dictionaries to a pandas DataFrame
48 df = pd.DataFrame(data)
49 # Specify the file path where you want to save the Excel file
50 file_name = 'projectile.xlsx'
51 # Save the DataFrame to an Excel file
52 df.to_excel(file_name, index=False)
53 print(f"Data generated within the for loop saved to '{file_name}' successfully.")
54
56 g=9.8 # accelaration due to gravity
57 R=U**2*sin(2*rtheta)/g # Theoretical value of Range, R
58 H=U**2*sin(rtheta)**2/(2*g) # Theoretical value of Height, H
59 T=2*U*sin(rtheta)/g # Theoretical value of time of flight, T
60 print('R=',R)
61 print('H=',H)
62 print('T=',T)
63
64 Rsim=max(xdata) # Simulated value of Range,R
65 Hsim=max(ydata) # Simulated value of Height, H
66 print('Rsim=',Rsim)
115
67 print('Hsim=',Hsim)
68
69 plot(xdata,ydata,'r*')
70 xlabel('Horizontal distance,x')
71 ylabel('Vertical distance,y')
72 title('Projectile motion')
73 grid()
74 show()
Output
IDLE Shell 3.10.4
>> Enter initial velocity(m/s),U:45
> Enter angle of projection:45
Enter time step,h:0.01
R= 206.6326516782168
H= 51.652186492147095
T= 6.493462111822251
Rsim= 206.5224815819093
Hsim= 51.493204487290384
Output
Enter initial velocity(m/s),U:45
Enter angle of projection:45
Enter time step,h:0.01
t x y vx vy
0.0100 0.3182 0.3172 31.8216 31.7200
0.0200 0.6364 0.6334 31.8216 31.6220
0.0300 0.9546 0.9487 31.8216 31.5240
0.0400 1.2729 1.2629 31.8216 31.4260
0.0500 1.5911 1.5762 31.8216 31.3280
0.0600 1.9093 1.8885 31.8216 31.2300
0.0700 2.2275 2.1998 31.8216 31.1320
0.0800 2.5457 2.5102 31.8216 31.0340
0.0900 2.8639 2.8195 31.8216 30.9360
0.1000 3.1822 3.1279 31.8216 30.8380
0.1100 3.5004 3.4353 31.8216 30.7400
0.1200 3.8186 3.7417 31.8216 30.6420
0.1300 4.1368 4.0472 31.8216 30.5440
0.1400 4.4550 4.3516 31.8216 30.4460
0.1500 4.7732 4.6551 31.8216 30.3480
-----------------------------------------------------
-----------------------------------------------------
-----------------------------------------------------
6.3700 202.7039 3.5415 31.8216 -30.6080
6.3800 203.0221 3.2344 31.8216 -30.7060
6.3900 203.3403 2.9264 31.8216 -30.8040
6.4000 203.6585 2.6174 31.8216 -30.9020
6.4100 203.9767 2.3074 31.8216 -31.0000
6.4200 204.2950 1.9964 31.8216 -31.0980
6.4300 204.6132 1.6844 31.8216 -31.1960
6.4400 204.9314 1.3715 31.8216 -31.2940
6.4500 205.2496 1.0576 31.8216 -31.3920
6.4600 205.5678 0.7427 31.8216 -31.4900
116
6.4700 205.8860 0.4268 31.8216 -31.5880
6.4800 206.2043 0.1099 31.8216 -31.6860
6.4900 206.5225 -0.2079 31.8216 -31.7840
R= 206.6326516782168
H= 51.652186492147095
T= 6.493462111822251
Rsim= 206.5224815819093
Hsim= 51.493204487290384
Folder view
117
4. Load the data in a excel file (.xlsx) and plot the data(say from the previous projectile motion
simulation from the file ‘projectile.xlsx’ and plot x vs y)
Script file
Program_132.py
1 import pandas as pd
2 import matplotlib.pyplot as plt
3
4 # Load the Excel file into a pandas DataFrame
5 file_name = 'projectile.xlsx'
6 df = pd.read_excel(file_name)
7
8 # Assuming the DataFrame has columns 'x' and 'y'
9 # Replace 'x' and 'y' with your column names
10 x = df['x']
11 y = df['y']
12
13 # Plot the data using matplotlib
14 plt.plot(x, y,'r', marker='o', linestyle='-')
15 plt.title('Projectile motion')
16 plt.xlabel('Range(m)')
17 plt.ylabel('Height(m)')
18 plt.grid(True)
118
19 plt.show()
Output
119
x=3
print(x)
12. Given x=[0,1,2,3,4,5,6,7,8,9], write a python code to pick the even numbers from the list using
slicing
13. Distinguish between List and Tuple
14. Write any four dictionary functions
15. Discuss the steps involved in the development of a program
16. Discuss looping techniques in python
17. Write a short note on file input and output pickling
18. Write a short note on operators in python programming
19. What are strings? How will you identify strings in pyton?
20. How will you use python as a calculator?
21. What are the advantages of python over other programming languages?
22. Given the result of the following python code
(a) for i in ‘india’:
print (i)
(b) a=[2,4,9,6,17]
insert(2,-1)
(c) range (0,10,0.5)
(d) (7+4)/2.0 *2-8%5
23. Differentiate between input() and raw_input () in python 2.0 with example
24. What are keywords in python, give few examples
25. Discuss various file operations in python
26. What are dictionaries and sequences?
27. Explain two modes of using python interpreter. What is python IDE?
28. What are the two modes of using python
29. List arithmetic operators in python
30. Explain range() in python
31. How to find the union and intersection of two sets in python?
32. What is the output of the code
f=1
for i in range (2,5):
f=f*i
print (f)
Section B
120
33. Develop a python program to read 10 words from a file and check each word is a palindrome
or not.
34. Write down the following iteration commands in python with example
a. while
b. for
35. Write a python program to find the mth root of a number
36. Differentiate between functions and modules in python. Discuss with suitable example how to
declare and call functions in python.
37. What is python? Discuss its features. Discuss the advantages of python over other languages.
38. What is python? Discuss its features. List and explain the rules for local variable and global
variable in python.
39. Create a user defined module to create all the arithmetic operations in python. Explain with the
help of example demonstrate how to call a function from your user defined module
40. Explain file input and output in python. Explain how to add new data into an existing file with
the help of an example.
Section C
41. What are the different data types in python. Explain with the help of suitable example
42. What are the different operators in python
Note: 4.5 is a floating number type function, type() will return the type of data type
>>>a=3+4j
121
>>>print(a)
(3+4j)
>>>a.real
3.0
>>>a.imag
4.0
4. Write Python code to remove the last two characters of 'I am a long string' by slicing, without
counting the characters. (hint: use negative indexing)
5. s = '012345' . (a) Slice it to remove last two elements (b) remove first two element.
Note
String 0 1 2 3 4 5
Index no 0 1 2 3 4 5
Python 2x
Python 3x
122
7. Print the following pattern using a while loop
+
++
+++
++++
Script file
Output
16 120
7 8
10. Write a program to print a decimal integer in octal and hexadecimal number system using formatted
printing
123
11. Write a Python program to print the multiplication table of any integer with numbers form 1 to 12.
Script file
Output
12. Write a program to find the volume of a box with sides 3,4 and 5 inches in cm3 ( 1 inch =
2.54 cm)
13. Write a program to find the percentage of volume occupied by a sphere of diameter r fitted
in a cube of side r. Read r from the keyboard.
Script file
Output
14. Count the number of times the character 'a' appears in a String read from the keyboard.
124
15. Create an adding machine that will keep on asking the user for numbers, add them together
and show the total after each step. Terminate when user enters a zero.
Script file
Result
16. Create a script that will convert Celsius to Fahrenheit. The program should ask the users to
enter the temperature in Celsius and should print out the temperature in Fahrenheit.
Script file
Result
Script file
Result
125
18. Write the multiplication table of a number, from the user, using for loop.
Script file
Result
19. Print the powers of 2 up to 1024 using a for loop. (only two lines of code)
Script file
Result
21. Write a program to find the average of n numbers read from the keyboard.
Script file
126
Result
22. Write a program to read numbers from the keyboard until their sum exceeds 200.
Script file
Result
Script file
Result
127
24. Write a Python function to calculate the GCD of two number
25. Write a Python program to find annual compound interest. Get P,N and R from user
26. Write a program to find the largest and smallest from a set of numbers entered through keyboard.
(write with and with out using the list functions)
27. Write a program to read and sort a set of numbers in ascending order.
28. Write a program to read a string and print in the reverse order.
Script file
Result
Script file
Result
128
30. Write a Python program write your name and address to a text file.
Script file
Text file
31. Write a Python program to read the data from the previous data file.
Script file
32. Make a list and write it to a file using the pickle module and read it
Script file
129
reading
33. Define the list [1,2,3,4,5,6]. Write code to insert a 10 after 2, delete 4, add 0 at the end and sort it in the
ascending order.
Script file
Result
34.Join the elements of the list ['I', 'am', 'in', 'pieces'] using + character. Do the same using a for loop also.
Script file
Result
Script file
Result
130
Script file
Result
36. Read a String from the keyboard. Multiply it by an integer to make its length more than 50. How do you
find out the smallest number that does the job
Script file
Result
37. Write a program to find the length of the hypotenuse of a right triangle from the length of other two sides,
get the input from the user
Script file
Result
38. Use the equation x = (-b ± √𝑏 − 4𝑎𝑐)/2a to find the roots of 3x2 + 6x + 12 = 0
Script file
131
Result
Note: Here instead of module math, cmath is used since the result can be complex as well
39. Write a program to calculate the distance between points (x1,y1) and (x2,y2) in a Cartesian plane. Get
the coordinates from the user.
Script file
Result
Script file
132
Chapter-2
The numpy and matplotlib(pylab) modules
133
2 Chapter-2: The numpy and pylab modules
Matrices: The matrix objects are strictly 2-dimensional whereas the ndarray objects can be multi-
dimensional. To create arrays in Python, use the Numpy library.
134
1 array([]) An array of any dimension can be created
array([]) 1D
array([[]]) 2D
array([[[]]]) 3D
2 arange(start,stop,step) Only 1D array can be created
3 linspace(start,stop,number of elements) Only 1D array can be created
4 zeros([x,y],datatype) or An array consists of only zero
zeros((x,y),datatype)
5 ones([x,y],datatyp) or An array consists of only one
ones((x,y),,datatyp)
6 random.random([x,y]) or Array consists of random numbers
random.random((x,y))
7 identity() Create an identity matrix
8 reshape(a,[newshape]) Reshape array a into a desired dimension
2.2.1 array ()
For creating array, you have to import numpy module first, then assign array to a
variable(optional). Use the function array() to create array, either using a square bracket(list)
or using parenthesis (tuple).It can be used for create multidimensional arrays. Examples are
given below
135
2.Create a two-dimensional array consisting of 6 elements, two raw and three column
Script file
Program_67.py
1 import numpy as np
2 a=np.array([[1,2,3],[7,4,1]])
3 print(a)
4 print(‘type=’,type(a))
5 print(‘dimension=’,np.ndim(a))
Output
IDLE Shell 3.10.4
>>> [[1 2 3]
[7 4 1]]
type= <class 'numpy.ndarray'>
dimension= 2
Script file
Program_68.py
1 import numpy as np
2 a=np.array([[1,2],[5,3],[4,1]])
3 print(a)
Output
IDLE Shell 3.10.4
>>> [[1 2]
[5 3]
[4 1]]
4.Create a three-dimensional array consisting of 12 elements, three raw and four column
Script file
Program_69.py
1 import numpy as np
2 a=np.array([[[3,7,1,4],[1,6,22,1],[9,7,8,3]]])
3 print(a)
4 print(‘type=’,type(a))
5 print(‘dimension=’,np.ndim(a))
Output
IDLE Shell 3.10.4
>>> [[[ 3 7 1 4]
[ 1 6 22 1]
[ 9 7 8 3]]]
type= <class 'numpy.ndarray'>
136
dimension= 3
Creates an evenly spaced one-dimensional array. Start, stop, stepsize and datatype are the arguments.
If datatype is not given, it is deduced from the other arguments. Note that, the values are generated
within the interval, including start but excluding stop.
Depending on the requirement, any one of the following syntax can be used
arange(stop)
arange(start,stop)
arange(start,stop,step)
arange(start,stop,step,dtype=datatype)
arange(start,stop,step,’datatype’)
Script file
Program_71.py
1 import numpy as np
2 a=np.arange(10)
3 print(a)
Output
IDLE Shell 3.10.4
137
>>> [0 1 2 3 4 5 6 7 8 9]
2. Create an array using arange function with elements between 5 and 25 with a step size of 5
Script file
Program_72.py
1 import numpy as np
2 a=np.arange(5,26,5)
3 print(a)
Output
IDLE Shell 3.10.4
>>> [ 5 10 15 20 25]
3. Create an array using arange function with elements between 5 and 25 with a step size of 5 where
all elements are floating numbers
Script file
Program_73.py
1 import numpy as np
2 a=np.arange(5,26,5,dtype=float)
3 print(a)
Output
IDLE Shell 3.10.4
>>> [ 5. 10. 15. 20. 25.]
4. Create an array using arange function with elements between 2 and 16 with a step size of 2 where
all elements are integers
Script file
Program_74.py
1 import numpy as np
2 a=np.arange(2,17,2,'int')
3 print(a)
Output
IDLE Shell 3.10.4
>>> [ 2 4 6 8 10 12 14 16]
Similar to arange(). Start, stop and number of samples are the arguments.
138
1. Create an array using linspace() function with elements between 1 and 10 with total 10 elements
Script file
Program_75.py
1 import numpy as np
2 a=np.linspace(1,10,10)
3 print(a)
Output
IDLE Shell 3.10.4
>>> [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
2 Create an array using linspace() function with elements between 1 and 10 with total 20 elements
Script file
Program_76.py
1 import numpy as np
2 a=np.linspace(1,10,20)
3 print(a)
Output
IDLE Shell 3.10.4
>>> [ 1. 1.47368421 1.94736842 2.42105263 2.89473684
3.36842105 3.84210526 4.31578947 4.78947368 5.26315789
5.73684211 6.21052632 6.68421053 7.15789474 7.63157895
8.10526316 8.57894737 9.05263158 9.52631579 10. ]
Difference between arange and linspace: Third argument denote the steps between two near by elements
in the array in arange() whereas third argument denote the number of elements between start and stop,
including start and stop in linspace(). In arange(), element corresponding to stop is not included in the
array.
arange() linspace()
>>>arange(10,40,2) >>>linspace(10,40,2)
array([10,12,14,16,18,20,22,24,26,28,30,32,34,3 array(10.,40.)
6,38])
#40 is not included in the array #40 is included in the array
>>>arange(10,40,10) >>>linspace(10,40,10)
array([10,20,30]) array([10., 13.333333, 16.666667, 2.0,
23.33333, 33.333333, 36.3333333, 40.)
139
2.2.4 zeros (shape, datatype)
Returns a new array of given shape and type, filled zeros. The arguments are shape and datatype. For
example zeros( [3,2], 'oat') generates a 3 x 2 array filled with zeros as shown below. If not specified,
the type of elements defaults to int.
zeros(shape)
or
zeros((shape),datatype)
1. Create an 3x3 matrix with all elements are zero
Script file
Program_77.py
1 import numpy as np
2 a=np.zeros((3,3))
3 print(a)
Output
IDLE Shell 3.10.4
>>> [[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
140
>>> [0. 0. 0. 0. 0.]
4. Create an 1-D matrix with 5 elements, all elements are integer zero
Script file
Program_80.py
1 import numpy as np
2 a=np.zeros((5),dtype=int)
3 print(a)
Output
IDLE Shell 3.10.4
>>> [0 0 0 0 0]
Similar to the functions above, but the matrix is filled with random numbers ranging from 0 to 1, of
float type. For example, random.random([3,3]) will generate the 3x3 matrix;
random.random(shape)
141
Script file
Program_82.py
1 import numpy as np
2 a=np.random.random((3,2))
3 print(a)
Output
IDLE Shell 3.10.4
>>> [[0.24616614 0.66793991]
[0.81149117 0.34336498]
[0.92447554 0.5296439 ]]
If you repeat the program again, it will create an entirely new set o random numbers.
2.2.6.2 Creating integer random numbers between ‘a’ and ‘b’: random.randint(a,b,n)
142
>>> [25 61 46 75 61 78 26 15 14 93]
2.2.7 identity(shape)
identity(shape)
identity matrix are always square matrix,hence shape consists of only one digit denoting either row or
column. Some examples are given below.
Script file
Program_85.py
1 import numpy as np
2 a=np.identity((3))
3 print(a)
Output
IDLE Shell 3.10.4
>>> [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
We can also make multi-dimensions arrays by reshaping a one-dimensional array. The function
reshape() changes dimensions of an array. The total number of elements must be preserved.
reshape(array, newshape)
143
1. create a one dimensional matrix consisting of 12 elements and reshape into a 4x3 matrix
Script file
Program_86.py
1 import numpy as np
2 a=np.arange(1,13,1)
3 print('a=',a)
4 b=np.reshape(a,[4,3]) #instead of square bracket parenthesis
5 print('b=',b)
Output
IDLE Shell 3.10.4
>>> a= [ 1 2 3 4 5 6 7 8 9 10 11 12]
b= [[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Indexing
Same as string index starts from zero
Array 5 10 15 20 25
index 0 1 2 3 4
slicing
Script file
Program_87.py
1 import numpy as np
2 a=np.arange(5,30,5)
3 print('a=',a)
4 b=a[0:3]
5 print('b=',b)
Output
IDLE Shell 3.10.4
>>> a= [ 5 10 15 20 25]
b= [ 5 10 15]
144
The idea is that suppose you created an array and made a copy of it. When you modify the copy,
original array should not get affected. Consider the following example. Here a is the original array. A
copy b of it is made using the command a=b and another copy is made using another method
c=a.copy(). Here the first element of b and c is changed. According to the concept of copying, the
original array a should not change. Here you can see that the second method is the right way to make
a copy of an array.
145
3 print('b=',b)
4 c=b+5
5 print('c=b+5=',c)
Output
IDLE Shell 3.10.4
>>> b= [[ 3 7 2]
[ 6 1 0]
[ 7 10 60]]
c=b+5= [[ 8 12 7]
[11 6 5]
[12 15 65]]
b c=b+5
[[ 3 7 2] [[ 8 12 7]
[ 6 1 0] [11 6 5]
[ 7 10 60]] [12 15 65]]
b d=b*5
[[ 3 7 2] [[ 15 35 10]
[ 6 1 0] [ 30 5 0]
[ 7 10 60]] [ 35 50 300]]
146
2.5.2.1 Adding two arrays having identical shape
a b c=a+b
[[ 3 7 2] [[1 4 2] [[ 4 11 4]
[ 6 1 0] [9 2 3] [15 3 3]
[ 7 10 60]] [1 5 8]] [ 8 15 68]]
147
[9 2 3]
[1 5 8]]
d=a*b= [[ 3 28 4]
[ 54 2 0]
[ 7 50 480]]
a b d=a*b
[[ 3 7 2] [[1 4 2] [[ 3 28 4]
[ 6 1 0] [9 2 3] [ 54 2 0]
[ 7 10 60]] [1 5 8]] [ 7 50 480]]
a= [3 7 2] b= [1 4 2]
c=a x b
𝒊 𝒋 𝑘
𝑎×𝑏 = 𝑎 𝑎 𝑎 =𝒊 𝑎 𝑏 −𝑎 𝑏 − 𝒋(𝑎 𝑏 − 𝑎 𝑏 ) + 𝒛(𝑎 𝑏 − 𝑎 𝑏 )
𝑏 𝑏 𝑏
𝑖 𝑗 𝑘
𝑎 × 𝑏 = 3 7 2 = 𝒊(14 − 8) − 𝒋(6 − 2) + 𝒛(12 − 7) = 6𝑖 − 4𝑗 + 5𝑘
1 4 1
Script file
Program_92.py
1 import numpy as np
2 a=np.array([3,7,2])
3 print('a=',a)
4 b=np.array([1,4,2])
5 print('b=',b)
6 c=np.cross(a,b)
7 print('c=axb=',c)
Output
IDLE Shell 3.10.4
>>> a= [3 7 2]
b= [1 4 2]
c=axb= [ 6 -4 5]
148
2.5.2.4 Dot product
a= [3 7 2] b= [1 4 2]
c=a.b=(3i+7j+2k).(1i+4j+2k)=3+28+4=35
Script file
Program_93.py
1 import numpy as np
2 a=np.array([3,7,2])
3 print('a=',a)
4 b=np.array([1,4,2])
5 print('b=',b)
6 d=np.dot(a,b)
7 print('d=a.b=',d)
Output
IDLE Shell 3.10.4
>>> a= [3 7 2]
b= [1 4 2]
d=a.b= 35
1 2 3 1 2 1
3. find the dot product of the matrices, A= 4 5 6 , B= 2 4 6
7 8 9 7 2 5
149
1 2 3 1 2 1 1 + 4 + 21 2+8+6 1 + 12 + 15
A= 4 5 6 B= 2 4 6 𝐴. 𝐵 = 4 + 10 + 42 8 + 20 + 12 4 + 30 + 30 =
7 8 9 7 2 5 7 + 16 + 63 14 + 32 + 18 7 + 48 + 45
26 16 28
56 40 64
86 64 100
Script file
Program_95.py
1 import numpy as np
2 A=np.array([[1,2,3],[4,5,6],[7,8,9]])
3 B=np.array([[1,2,1],[2,4,6],[7,2,5]])
4 print('A=',A)
5 print('B=',B)
6 c=np.dot(A,B)
7 print('c=A.B=',c)
Output
IDLE Shell 3.10.4
>>> A= [[1 2 3]
[4 5 6]
[7 8 9]]
B= [[1 2 1]
[2 4 6]
[7 2 5]]
c=A.B= [[ 26 16 28]
[ 56 40 64]
[ 86 64 100]]
a b d=a.b
[[1 2 3] [[1 2 1] [[ 26 16 28]
[4 5 6] [2 4 6] [ 56 40 64]
[7 8 9]] [7 2 5]] [ 86 64 100]]
150
det(a)=3(6-6)-7(36-21) + 2(12-7)=0-105+10=-95
0 −15 5
cofactor matrix of a is −38 4 43
19 3 −39
0 −38 19
Transpose is −15 4 3
5 43 −39
Script file
Program_96.py
1 import numpy as np
2 a=np.array([[3,7,2],[6,1,3],[7,2,6]])
3 ainv=np.linalg.inv(a)
4 print(ainv)
Output
IDLE Shell 3.10.4
>>> [[ 7.93016446e-18 4.00000000e-01 -2.00000000e-01]
[ 1.57894737e-01 -4.21052632e-02 -3.15789474e-02]
[-5.26315789e-02 -4.52631579e-01 4.10526316e-01]]
4x1 - 2x2 + x3 = 11
-2x1 + 4x2- 2x3 =-16
x1 - 2x2 + 4x3 = 17
𝑥 4 −2 1 11
𝑥 −2 4 −2 = −16
𝑥 1 −2 4 17
4 −2 1 𝑥 11
−2 4 −2 𝑥 = −16
1 −2 4 𝑥 17
(𝐴𝑋) = 𝐵
𝑋=𝐴 𝐵
𝑥 4 −2 1 11
𝑥 = −2 4 −2 −16
𝑥 1 −2 4 17
𝑥 11
𝑎𝑑𝑗(𝐴)
𝑥 = −16
𝑥 |𝐴|
17
151
12 6 0
𝑥 6 15 6 11
𝑥 = 0 6 12
−16
𝑥 4𝑥12 + 2(−6) + 1(0)
17
12 6 0 11
𝑥 6 15 6 −16
𝑥 = 0 6 12 17
𝑥 36
12 6 0 11
𝑥 6 15 6 −16
𝑥 = 0 6 12 17
𝑥 36
36
𝑥 −72
𝑥 = 108
𝑥 36
𝑥 1
𝑥 = −2
𝑥 3
Script file
Program_97.py
1 import numpy as np
2 a=np.array([[4,-2,1],[-2,4,-2],[1,-2,4]])
3 print('a=',a)
4 b=np.array([[11],[-16],[17]])
5 print('b=',b)
6 c= np.linalg.inv(a)
7 print('c=',c)
8 x=np.dot(c,b)
9 print('x=',x)
Output
IDLE Shell 3.10.4
>>> a= [[ 4 -2 1]
[-2 4 -2]
[ 1 -2 4]]
b= [[ 11]
[-16]
[ 17]]
c= [[0.33333333 0.16666667 0. ]
[0.16666667 0.41666667 0.16666667]
[0. 0.16666667 0.33333333]]
x= [[ 1.]
[-2.]
[ 3.]]
152
2.6 Exercise
Ans: x=1.25,y=4,z=-0.75
a=arange(1,11,1)
153
∑(𝑥 − 𝑚)
𝑣=
𝑁−1
or
• import matplotlib.pyplot as plt
pyplot is the most commonly used submodule in matplotlib for plotting. This is the most typical
way of using matplotlib. You can then use the plt alias for various plotting functions
[recommended method]
or
154
• from matplotlib.pyplot import*
This approach is less recommended because it imports everything into the global namespace:
Or
• from matplotlib.pyplot import plot, show
If you only need a specific function, you can import it directly: You can now call the functions directly
without using the plt alias:
Or
• from pylab import*
Note:
➢ matplotlib is a comprehensive library for creating static, animated, and interactive
visualizations in Python. Within matplotlib, the pyplot module is the most commonly
used submodule for creating plots.
➢ pylab is a convenience module that comes with matplotlib. It combines
matplotlib.pyplot with NumPy into a single namespace, mimicking MATLAB’s
environment, where both plotting and mathematical operations are accessible without
needing separate imports.
For exam, you only need the following graphs. You must know how to add title and add labels
to axis, multiple plots, scale axis (xlim & ylim) and color plot
Plot the following graphs
Plot simple X and y data
sin(x) sin2(x)
cos(x) sin(x2)
exp(x)
polar plot
• Marka point in polar plot
• Make a circle in polar plot
• Archimedes spiral
• Fermat’s spiral
• Polar rose
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
155
Script file
Program_100.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 plt.plot(x,y)
5 plt.show()
Output
Figure 1
Same program can be written in the following way if you are importing module as from
matplotlib.pyplot import*
Script file
Program_100.py
1 from matplotlib.pyplot import*
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 plot(x,y)
5 show()
Output
Figure 1
156
2. Plot the following x & y data
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
157
Same program can be written in the following way if you are importing module as from
matplotlib.pyplot import*
Script file
Program_101.py
1 from matplotlib.pyplot import*
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 plot(x,y,'o-r')
5 title('xy graph')
6 xlabel('x-data')
7 ylabel('y-data')
8 grid()
9 show()
Output
Figure 1
158
3. Plot the following x & y data
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
Script file
Program_102.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 plt.plot(x,y,'--r',linewidth=4,marker='o',ms='10',mec='m',mfc='g')
5 #ms-marker size, mec= marker edge color, mfc=marker face color
6 plt.title('xy graph',fontsize=18)
7 plt.xlabel('x-data',fontsize=15)
8 plt.ylabel('y-data',fontsize=15)
9 plt.xlim(-2,15)
10 plt.ylim(-2,15)
159
11 plt.grid()
12 plt.show()
Output
Figure 1
Script file
Program_103.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 plt.plot(x,y,'--r',linewidth=4,marker='o',ms='10',mec='m',mfc='g')
5 plt.title('xy graph',fontsize=18)
6 plt.xlabel('x-data',fontsize=15)
7 plt.ylabel('y-data',fontsize=15)
8 plt.grid(axis=’x’)
9 plt.show()
Output
Figure 1
160
Grid lines
For horizontal grid lines: grid(axis=’x’)
For vertical grid lines: grid(axis=’y’)
Note
161
"x" Cross
"_" Horizontal line
"|" Vertical line
"s" Square
"d" Diamond
"^" Upward-pointing triangle
"v" Downward-pointing triangle
">" Right-pointing triangle
"<" Left-pointing triangle
"p" Pentagram
"h" Hexagram
“,” comma ,
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
Script file
Program_104.py
1 import matplotlib.pyplot as plt
162
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 z=[5,6,7,8,9,8,7,6,5,4]
5 plot(x,y,'--pr')
6 plot(x,z,':dg')
7 title('xy and xz graph',fontsize=18)
8 xlabel('x-data',fontsize=15)
9 ylabel('y/z-data',fontsize=15)
10 legend(['x vs y','x vs z'],loc='upper left')
11 xlim(-2,11)
12 ylim(-1,12)
13 grid()
14 show()
Output
Figure 1
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
Script file
Program_105.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
163
4 z=[5,6,7,8,9,8,7,6,5,4]
5
6 plt.figure(1)
7 plt.plot(x,y,'--pr')
8 plt.title('xy graph',fontsize=18)
9 plt.xlabel('x-data',fontsize=15)
10 plt.ylabel('y-data',fontsize=15)
11 plt.grid()
12
13 plt.figure(2)
14 plt.plot(x,z,':dg')
15 plt.title(' xz graph',fontsize=18)
16 plt.xlabel('x-data',fontsize=15)
17 plt.ylabel('z-data',fontsize=15)
18 plt.grid()
19
20 plt.show()
Output
Figure 1
Figure 2
164
Legend location options
‘best’
‘upper right’
‘upper left’
‘lower left’
‘lower right’
‘right’
‘center’
‘center left’
‘center right’
‘lower center’
‘upper center’
2.8.2 Subplot
6. Plot the above two plots as subplot in two side by side panel (one row and two column)
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
Script file
Program_106.py
1 import matplotlib.pyplot as plt
165
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 z=[5,6,7,8,9,8,7,6,5,4]
5
6 plt.subplot(1,2,1)
7 plt.plot(x,y,'--pr')
8 plt.title(' xy graph',fontsize=13)
9 plt.xlabel('x-data',fontsize=13)
10 plt.ylabel('y-data',fontsize=13)
11 plt.grid()
12
13 plt.subplot(1,2,2)
14 plt.plot(x,z,':dg')
15 plt.title(' xz graph',fontsize=13)
16 plt.xlabel('x-data',fontsize=13)
17 plt.ylabel('z-data',fontsize=13)
18 plt.grid()
19
20 plt.show()
Output
Figure 1
7. Plot the above two plots as subplot in upper and lower panel (two row and one column)
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
166
Script file
Program_107.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 z=[5,6,7,8,9,8,7,6,5,4]
5
6 plt.subplot(2,1,1)
7 plt.plot(x,y,'--pr')
8 plt.title(' xy graph',fontsize=13)
9 plt.xlabel('x-data',fontsize=13)
10 plt.ylabel('y-data',fontsize=13)
11 plt.grid()
12
13 plt.subplot(2,1,2)
14 plt.plot(x,z,':dg')
15 plt.title(' xz graph',fontsize=13)
16 plt.xlabel('x-data',fontsize=13)
17 plt.ylabel('z-data',fontsize=13)
18 plt.grid()
19
20 plt.show()
Output
Figure 1
167
7. Plot x vs y (top), x vs z (middle) and x vs w (bottom) using subplot.
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
w 2 2 2 2 2 2 2 2 2 2
Script file
Program_108.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 z=[5,6,7,8,9,8,7,6,5,4]
5 w=[2,2,2,2,2,2,2,2,2,2]
6
7 plt.subplot(3,1,1)
8 plt.plot(x,y,'--pr')
9 plt.title(' xy graph',fontsize=13)
10 plt.xlabel('x-data',fontsize=13)
11 plt.ylabel('y-data',fontsize=13)
12 plt.grid()
13
14 plt.subplot(3,1,2)
15 plt.plot(x,z,':dg')
16 plt.title(' xz graph',fontsize=13)
17 plt.xlabel('x-data',fontsize=13)
18 plt.ylabel('z-data',fontsize=13)
19 plt.grid()
20
21 plt.subplot(3,1,3)
22 plt.plot(x,w,':dg')
23 plt.title(' xw graph',fontsize=13)
24 plt.xlabel('x-data',fontsize=13)
25 plt.ylabel('w-data',fontsize=13)
26 plt.grid()
27
28 plt.show()
Output
Figure 1
168
8. Plot the above graph side by side using subplot
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
w 2 2 2 2 2 2 2 2 2 2
Script file
Program_109.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 z=[5,6,7,8,9,8,7,6,5,4]
5 w=[2,2,2,2,2,2,2,2,2,2]
6
7 plt.subplot(1,3,1)
8 plt.plot(x,y,'--pr')
9 plt.title(' xy graph',fontsize=13)
10 plt.xlabel('x-data',fontsize=13)
11 plt.ylabel('y-data',fontsize=13)
12 plt.grid()
13
14 plt.subplot(1,3,2)
15 plt.plot(x,z,':dg')
16 plt.title(' xz graph',fontsize=13)
17 plt.xlabel('x-data',fontsize=13)
18 plt.ylabel('z-data',fontsize=13)
169
19 plt.grid()
20
21 plt.subplot(1,3,3)
22 plt.plot(x,w,':dg')
23 plt.title(' xw graph',fontsize=13)
24 plt.xlabel('x-data',fontsize=13)
25 plt.ylabel('w-data',fontsize=13)
26 plt.grid()
27
28 plt.show()
Output
Figure 1
9. Plot the x vs y graph in the upper panel and x vs z and x vs w in two lower panel
x 1 2 3 4 5 6 7 8 9 10
y 1 2 3 4 5 6 7 8 9 10
z 5 6 7 8 9 8 7 6 5 4
w 2 2 2 2 2 2 2 2 2 2
Script file
Program_110.py
1 import matplotlib.pyplot as plt
2 x=[1,2,3,4,5,6,7,8,9,10]
3 y=[1,2,3,4,5,6,7,8,9,10]
4 z=[5,6,7,8,9,8,7,6,5,4]
5 w=[2,2,2,2,2,2,2,2,2,2]
6
7 plt.subplot(2,1,1)
170
8 plt.plot(x,y,'--pr')
9 plt.title(' xy graph',fontsize=13)
10 plt.xlabel('x-data',fontsize=13)
11 plt.ylabel('y-data',fontsize=13)
12 plt.grid()
13
14 plt.subplot(2,2,3)
15 plt.plot(x,z,':dg')
16 plt.title(' xz graph',fontsize=13)
17 plt.xlabel('x-data',fontsize=13)
18 plt.ylabel('z-data',fontsize=13)
19 plt.grid()
20
21 plt.subplot(2,2,4)
22 plt.plot(x,w,':dg')
23 plt.title(' xw graph',fontsize=13)
24 plt.xlabel('x-data',fontsize=13)
25 plt.ylabel('w-data',fontsize=13)
26 plt.grid()
27
28 plt.show()
Output
Figure 1
171
Subplot command for different command is as follows
Subplot(2,2,x) Subplot(3,3,x)
Subplot(2,3,x) Subplot(3,2,x)
(2,2,1) (2,2,2)
(1,2,2) (1,2,1)
(2,2,3) (2,2,4)
Script file
Program_111.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(1,10,10) #now x is an array
4 y1=x
5 y2=x**2 #you can take square of only array, not list
6 y3=x**3
7 y4=x**4
8 y5=x**5
9 y6=x**6
10 y7=x**7
11 y8=x**8
12
13 plt.subplot(4,2,1)
172
14 plt.plot(x,y1,'--dr',linewidth=2,markersize=10)
15 plt.grid()
16
17 plt.subplot(4,2,2)
18 plt.plot(x,y2,'--sb',linewidth=2,markersize=10)
19 plt.grid()
20
21 plt.subplot(4,2,3)
22 plt.plot(x,y3,'-->m',linewidth=2,markersize=8)
23 plt.grid()
24 plt.ylabel('y-data')
25
26 plt.subplot(4,2,4)
27 plt.plot(x,y4,'--<k',linewidth=2,markersize=8)
28 plt.grid()
29 plt.ylabel('y-data')
30
31 plt.subplot(4,2,5)
32 plt.plot(x,y5,'--*c',linewidth=2,markersize=8)
33 plt.grid()
34
35 plt.subplot(4,2,6)
36 plt.plot(x,y6,'-.pg',linewidth=2,markersize=8)
37 plt.grid()
38
39 plt.subplot(4,2,7)
40 plt.plot(x,y7,':+y',linewidth=2,markersize=8)
41 plt.grid()
42 plt.xlabel('x-data')
43
44 plt.subplot(4,2,8)
45 plt.plot(x,y8,'--or',linewidth=2,markersize=8)
46 plt.grid()
47 plt.xlabel('x-data')
48
49 plt.show()
Output
Figure 1
173
Same program can be written in the following way if you are importing module as from
matplotlib.pyplot import* and from numpy import*
Script file
Program_111.py
1 from matplotlib.pyplot import*
2 from numpy import*
3 x=linspace(1,10,10)
4 y1=x
5 y2=x**2
6 y3=x**3
7 y4=x**4
8 y5=x**5
9 y6=x**6
10 y7=x**7
11 y8=x**8
12
13 subplot(4,2,1)
14 plot(x,y1,'--dr',linewidth=2,markersize=10)
15 grid()
16
17 subplot(4,2,2)
18 plot(x,y2,'--sb',linewidth=2,markersize=10)
19 grid()
20
21 subplot(4,2,3)
174
22 plot(x,y3,'-->m',linewidth=2,markersize=8)
23 grid()
24 ylabel('y-data')
25
26 subplot(4,2,4)
27 plot(x,y4,'--<k',linewidth=2,markersize=8)
28 grid()
29 ylabel('y-data')
30
31 subplot(4,2,5)
32 plot(x,y5,'--*c',linewidth=2,markersize=8)
33 grid()
34
35 subplot(4,2,6)
36 plot(x,y6,'-.pg',linewidth=2,markersize=8)
37 grid()
38
39 subplot(4,2,7)
40 plot(x,y7,':+y',linewidth=2,markersize=8)
41 grid()
42 xlabel('x-data')
43
44 subplot(4,2,8)
45 plot(x,y8,'--or',linewidth=2,markersize=8)
46 grid()
47 xlabel('x-data')
48
49 show()
Or instead of using both numpy and matplotlib module, you can use a single
modue pylab as shown below
Script file
Program_111.py
1 from pylab import*
2 x=linspace(1,10,10)
3 y1=x
y2=x**2
4
y3=x**3
5 y4=x**4
6 y5=x**5
7 y6=x**6
8 y7=x**7
9 y8=x**8
10
subplot(4,2,1)
11
plot(x,y1,'--dr',linewidth=2,markersize=10)
12 grid()
13
14 subplot(4,2,2)
175
15 plot(x,y2,'--sb',linewidth=2,markersize=10)
16 grid()
17
subplot(4,2,3)
18
plot(x,y3,'-->m',linewidth=2,markersize=8)
19 grid()
20 ylabel('y-data')
21
22 subplot(4,2,4)
23 plot(x,y4,'--<k',linewidth=2,markersize=8)
24 grid()
ylabel('y-data')
25
26 subplot(4,2,5)
27 plot(x,y5,'--*c',linewidth=2,markersize=8)
28 grid()
29
30 subplot(4,2,6)
31 plot(x,y6,'-.pg',linewidth=2,markersize=8)
grid()
32
33 subplot(4,2,7)
34 plot(x,y7,':+y',linewidth=2,markersize=8)
35 grid()
36 xlabel('x-data')
37
subplot(4,2,8)
38
plot(x,y8,'--or',linewidth=2,markersize=8)
39 grid()
40 xlabel('x-data')
41
42 show()
2.8.3 Plotting sin (x), cos (x), sin2 (x) and sin (x2)
1. plot sin(x)
To plot anything, we need x-axis and y-axis data. For trigonometric functions x data is degree or
multiples of 𝜋 and here y axis is a function, y=sin(x). Let’s take x data from 0 to +8 𝜋 [2 𝜋 is one
oscillation. 0 to +8 𝜋 consists of 4 oscillations]
Here 𝜋 =3.14
Here we have used pylab module, which is a combination of matplotlib and numpy
Script file
Program_112.py
1 import pylab as pl
2 x=pl.linspace(0, 8*pl.pi,1000) #1000 data points between 0 and 8*pi
3 y=pl.sin(x)
4 pl.plot(x,y,'r')
5 pl.xlabel('x')
176
6 pl.ylabel('Amplitude')
7 pl.title('sin(x)')
8 pl.xlim([-1*pl.pi,10*pl.pi])# adjust the length of x axis
9 pl.ylim([-2,2]) # adjust the length of y axis
10 pl.grid()
11 pl.show()
Output
Figure 1
Script file
Program_113.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(-5*np.pi, 5*np.pi,1000) #1000 data points between -5*pi
4 and 5*pi
5 y=5*np.sin(5*x) #A sin(ωt),A is the amplitude, ω is the frequency
6 plt.plot(x,y,'r')
7 plt.xlabel('x')
8 plt.ylabel('Amplitude')
9 plt.title('sin(x)')
10 plt.grid()
11 plt.show()
Output
Figure 1
177
3. plot cos(x)
Script file
Program_114.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(0, 5*np.pi,1000) #1000 data points between 0 and 5*pi
4 y=np.cos(x)
5 plt.plot(x,y,'b')
6 plt.xlabel('x')
7 plt.ylabel('Amplitude')
8 plt.title('cos(x)')
9 plt.grid()
10 plt.show()
Output
Figure 1
178
5. plot sin (x), cos (x), sin2(x), sin(x2) in single figure in four panels
Script file
Program_115.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(-5*np.pi, 5*np.pi,3000) #3000 data points between -5*pi
4 and 5*pi
5 y1=np.sin(x)
6 plt.subplot(2,2,1)
7 plt.plot(x,y1,'r')
8 plt.xlabel('x')
9 plt.ylabel('Amplitude')
10 plt.legend(['sin (x)'],loc='upper left')
11 plt.grid()
12
13 y2=np.cos(x)
14 plt.subplot(2,2,2)
15 plt.plot(x,y2,'b')
16 plt.xlabel('x')
17 plt.ylabel('Amplitude')
18 plt.legend(['cos (x)'],loc='upper left')
19 plt.grid()
20
21 y3=np.sin(x)**2
22 plt.subplot(2,2,3)
179
23 plt.plot(x,y3,'g')
24 plt.xlabel('x')
25 plt.ylabel('Amplitude')
26 plt.legend(['sin(x)**2'],loc='upper left')
27 plt.grid()
28
29 y4=np.sin(x**2)
30 plt.subplot(2,2,4)
31 plt.plot(x,y4,'m')
32 plt.xlabel('x')
33 plt.ylabel('Amplitude')
34 plt.legend(['sin(x**2)'],loc='upper left')
35 plt.grid()
36
37 plt.show()
Output
Figure 1
6. plot y1=5*sin (x), y2=5*cos (x) and y3= y2+y3=5*sin (x)+ 5*cos (x), using suplots which is of the
form y= A sin x+ B cos x
Script file
Program_116.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(0, 5*np.pi,1000) #1000 data points between -5*pi and 5*pi
4 y1=5*np.sin(x)
5 y2=5*np.cos(x)
180
6 y3=y1+y2
7
8 plt.subplot(3,1,1)
9 plt.plot(x,y1,'r')
10 plt.legend(['5*sin(x)'])
11 plt.grid()
12
13 plt.subplot(3,1,2)
14 plt.plot(x,y3,'b')
15 plt.legend(['5*cos(x)'])
16 plt.grid()
17
18 plt.subplot(3,1,3)
19 plt.plot(x,y3,'g')
20 plt.legend(['5*sin(x)+5*cos(x)'])
21 plt.grid()
22 plt.show()
Output
Figure 1
7. Add a sine with another sine wave which is 1800 phase shifted. Obtain the resulting wave form.
Script file
Program_117.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(0, 5*np.pi,1000)
181
4 y1=np.sin(x)
5 y2=np.sin(x+np.pi)
6 y3=y1+y2
7
8 plt.subplot(2,1,1)
9 plt.plot(x,y1,'r')
10 plt.plot(x,y2,'b')
11 plt.legend(['sin(x)','sin (x+pi)'])
12 plt.grid()
13
14 plt.subplot(2,1,2)
15 plt.plot(x,y3,'g')
16 plt.legend(['sin(x)+sin(x+pi)'])
17 plt.ylim([-1,1])
18 plt.grid()
19 plt.show()
Output
Figure 1
Polar cordinats locate a point on a plane with one distance and one angle. The distance ‘r’ is measured
from origin. The angel ‘’ is measured from positive direction of x-axis in the anti-clockwise sense.
182
Note: In polar plot angle is always taken as multiples of pi not in degree.
Script file
Program_118.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 r=5
4 theta=np.pi
5 plt.polar(theta,r,'or',ms=10)
6 plt.show()
Output
Figure 1
2.Daraw a polar plot having a radius 2, where theta scans from 00 to 1800 (Draw a semi circile)
Script file
Program_119.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 r=2*np.ones(180)
4 theta=np.linspace(0,np.pi,180)
5 plt.polar(theta,r,'-m',linewidth=3)
6 plt.show()
Output
Figure 1
183
3.Draw a complete circle having radius 5 cm using polar plot
Script file
Program_120.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 r=5*np.ones(360)
4 theta=np.linspace(0,2*np.pi,360)
5 plt.polar(theta,r,'r*')
6 plt.show()
Output
Figure 1
184
Special polar plots
Script file
Program_121.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 k=2
4 theta=np.linspace(0,10*np.pi,1000)
5 r=k*theta
6 plt.polar(theta,r,'m')
7 plt.show()
Output
Figure 1
Script file
Program_122.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 k=5
185
4 theta=np.linspace(0,10*np.pi,1000)
5 r=np.sqrt(k**2*theta)
6 plt.polar(theta,r,'r')
7 plt.polar(theta,-r,'b')
8 plt.show()
Output
Figure 1
Script file
Program_123.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 k=6 #decides number of petals in the flower
4 theta=np.linspace(0,10*np.pi,1000)
5 r=np.cos(k*theta)
6 plt.polar(theta,r,'b')
7 plt.show()
Output
Figure 1
186
2.8.5 Exponential plot
Script file
Program_124.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 x=np.linspace(1,10,100)
4 y=np.exp(x)
5 plt.plot(x,y,'+m')
6 plt.grid()
7 plt.xlabel('x')
8 plt.ylabel('exp(x)')
9 plt.title('exponential plot')
10 plt.show()
Output
Figure 1
187
2.9 Previous year questions
188
14. Write a program using linspace to plot sin2x , cos x, sin x2(2 mark).
1. Write code to make a one dimensional matrix with elements 5,10,15,20 and 25. make another
matrix by slicing the frst three elements from it.
2. Create a 3 × 2 matrix and print the sum of its elements using for loops.
3. Create a 2 × 3 matrix and fill it with random numbers.
4. Use linspace to make an array from 0 to 10, with stepsize of 0.1
5. Use arange to make an 100 element array ranging from 0 to 10.
6. Make a 3x3 matrix and multipy it by 5.
7. Create two 3x3 matrices and add them.
8. Write programs to demonstrate the dot and cross products.
Script file
Program_132.py
1 from pylab import*
2 x=linspace(0,5*pi,1000)
3 y=sin(x)
4 plot(x,y,'-r')
5 xlabel('$\pi$')
6 ylabel('Amplitude')
7 grid()
8 show()
Output
Figure 1
189
2. Plot the above sin wave from -5 𝜋 to +5 𝜋 and limit the x axis from -6 𝜋 to +6 𝜋 and y axis from -2
to +2 . Also add a legend ‘sin (x)’
Script file
Program_133.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y=sin(x)
4 plot(x,y,'-r')
5 xlabel('$\pi$')
6 ylabel('Amplitude')
7 xlim(-6*pi,6*pi)
8 ylim(-2,2)
9 legend([‘sin(x)’])
10 grid()
11 show()
Output
Figure 1
190
3. Plot a sin wave and a cosine wave from -5 𝜋 to +5 𝜋 . Give different color to both graph
Script file
Program_134.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y1=sin(x)
4 y2=cos(x)
5 plot(x,y1,'-r')
6 plot(x,y2,'--b')
7 xlabel('$\pi$')
8 ylabel('Amplitude')
9 legend(['sin(x)','cos(x)'])
10 grid()
11 show()
Output
Figure 1
191
4. In the above graph increase the amplitude of the graph to 10
Script file
Program_135.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y1=10*sin(x) #Here amplitude is increased by multiplying a number
4 with the sine term
5 y2=cos(x)
6 plot(x,y1,'-r')
7 plot(x,y2,'--b')
8 xlabel('$\pi$')
9 ylabel('Amplitude')
10 legend(['sin(x)','cos(x)'])
11 grid()
12 show()
Output
Figure 1
192
5. In the above graph increase the frequency of the cosine wave
Script file
Program_136.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y1=10*sin(x)
4 y2=cos(5*x) # Here frequency is increased by multiplying a number to
5 the term inside the bracket
6 plot(x,y1,'-r')
7 plot(x,y2,'--b')
8 xlabel('$\pi$')
9 ylabel('Amplitude')
10 legend(['sin(x)','cos(x)'])
11 grid()
12 show()
Output
Figure 1
193
6. Create two sin waves having equal amplitude, introduce a phase shift of 450 (pi/4) to one of the sine
wave
Script file
Program_137.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y1=sin(x)
4 y2=sin(x+pi/4) #Here phase shift is introduced by adding a value to
5 the term inside bracket
6 plot(x,y1,'-r')
7 plot(x,y2,'--r')
8 xlabel('$\pi$')
9 ylabel('Amplitude')
10 legend(['sin(x)','sin(x+$\pi/4$)'])
11 grid()
12 show()
Output
Figure 1
194
7. Create two sin waves having equal amplitude, introduce a phase shift of 180 0 (pi) to one of the sine
wave
Script file
Program_138.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y1=sin(x)
4 y2=sin(x+pi) #Here phase shift is introduced by adding a value to the
5 term inside bracket
6 plot(x,y1,'-r')
7 plot(x,y2,'--r')
8 xlabel('$\pi$')
9 ylabel('Amplitude')
10 legend(['sin(x)','sin(x+$\pi$)'])
11 grid()
12 show()
Output
Figure 1
195
8. Create two sin waves having equal amplitude, Add a dc voltage of 10 V to one of the sine waves
Script file
Program_139.py
1 from pylab import*
2 x=linspace(-5*pi,5*pi,1000)
3 y1=sin(x)
4 y2=10+sin(x) #Here DC is introduced by adding a number to the sine
5 term
6 plot(x,y1,'-r')
7 plot(x,y2,'--r')
8 xlabel('$\pi$')
9 ylabel('Amplitude')
10 legend(['sin(x)','10+sin(x$)'])
11 grid()
12 show()
Output
Figure 1
196
9. Add two sine waves having slightly different frequency and demonstrate the formation of beats. Plot
the graph from -25 𝝅 to +25 𝝅.
Script file
Program_140.py
1 from pylab import*
2 x=linspace(-25*pi,25*pi,10000)
3 y1=sin(2*x) # here frequency is 2
4 y2=sin(2.1*x) # here frequency is 2.1
5 y3=y1+y2
6
7 subplot(3,1,1)
8 plot(x,y1,'-r')
9 legend(['sin(2x)'])
10 grid()
11
12 subplot(3,1,2)
13 plot(x,y2,'--b')
14 legend(['sin(2.1x)'])
15 grid()
16
17 subplot(3,1,3)
18 plot(x,y3,':g')
19 xlabel('$\pi$')
197
20 ylabel('Amplitude')
21 legend(['sin(2x)+sin(2.1x)'])
22 grid()
23 show()
Output
Figure 1
198
Other exotic plots (Not a part of syllabus)
Archimedes spiral Archimedes spiral
from pylab import* from pylab import*
k=5 k=5
theta=linspace(0,20*pi,100) theta=linspace(0,20*pi,100)
r=k*theta r=k*theta
polar(theta,r) polar(theta,r)
show() show()
199
polar(theta,-r1,'*b')
show()
show()
200
201
Chapter-3
Numerical Methods-I
202
Ref:
203
3 Chapter-3: Numerical Methods-I
Closed-Form Solutions: Analytical methods aim to find exact, closed-form solutions to mathematical
problems. These solutions are expressed in terms of algebraic expressions, trigonometric functions,
logarithmic functions, or other well-defined mathematical functions.
Theoretical Precision: Analytical solutions provide a high level of theoretical precision. Once obtained,
they are exact and apply to all cases covered by the assumptions made during the analytical process.
Limited Applicability: Analytical methods are often limited to solving problems with well-defined
mathematical structures and simple boundary conditions. They may struggle with complex or nonlinear
systems and equations.
Examples: Solving algebraic equations, finding derivatives and integrals, solving linear differential
equations with constant coefficients, etc., are examples of problems often addressed analytically.
Algorithms and Computations: Numerical methods use algorithms and computational procedures to
solve problems. These algorithms are implemented on computers to perform calculations and iterations,
making them well-suited for problems that lack analytical solutions.
Applicability to Complex Problems: Numerical methods are particularly useful for solving complex
problems, especially those involving nonlinear equations, partial differential equations, and situations
where analytical solutions are difficult or impossible to obtain.
Error Considerations: Numerical solutions are typically subject to some level of error due to the use of
approximations. Various numerical techniques aim to control and minimize these errors.
204
Examples: Finite difference methods, finite element methods, numerical integration, root-finding
algorithms, and iterative methods for solving differential equations are examples of numerical
approaches.
Nature of Solutions: Analytical methods provide exact, closed-form solutions, while numerical methods
offer approximate solutions through computational techniques.
Precision: Analytical methods provide theoretically precise solutions, whereas numerical methods may
introduce errors due to approximations.
Applicability: Analytical methods are well-suited for problems with clear mathematical structures,
while numerical methods are more versatile and applicable to a broader range of problems, especially
those with complexity or lack of analytical solutions.
In practice, the choice between numerical and analytical methods depends on the specific characteristics
of the problem, the availability of analytical solutions, and computational resources. Often, a
combination of both approaches is employed for comprehensive problem-solving.
a. Applicability to Complex Problems: Numerical methods are often more suitable for solving
complex problems that lack closed-form analytical solutions. Many real-world problems in
physics, engineering, finance, and other fields involve intricate equations that cannot be solved
analytically.
b. Flexibility: Numerical methods are more flexible in handling a wide range of mathematical
models and equations. They can be applied to problems with irregular geometries, complex
boundary conditions, and nonlinear relationships.
c. Computational Efficiency: For certain problems, numerical methods can be more
computationally efficient than analytical methods. Analytical solutions may not exist or may
be too difficult and time-consuming to obtain, whereas numerical methods can provide
approximate solutions with reasonable computational effort.
d. Adaptability to Computer Implementation: Numerical methods are well-suited for
implementation on computers, making them applicable to problems that involve extensive
calculations. Modern computational tools and software packages enable the efficient
application of numerical methods to a wide range of problems.
205
e. Handling Nonlinearity: Many real-world problems involve nonlinearities that complicate the
analytical solution process. Numerical methods can handle nonlinear equations more readily,
allowing for the analysis of systems with complex behaviours.
f. Solution of Differential Equations: Numerical methods are often essential for solving ordinary
and partial differential equations, especially when analytical solutions are not available. These
equations describe many physical phenomena, and numerical techniques like finite difference
or finite element methods are commonly used for their solution.
g. Experimental Validation: Numerical methods can be used to validate experimental results. In
situations where obtaining analytical solutions is impractical, numerical simulations can
provide insights and predictions that can be compared with experimental data.
h. Iterative Improvement: Numerical methods often involve iterative processes that allow for the
improvement of solutions through successive approximations. This iterative nature can be
advantageous in refining solutions until a satisfactory level of accuracy is achieved.
• Bisection method
• Newton-Raphson method
This method states that if a function f(x) is continuous between a and b and f(a) and f(b) are opposite
signs then there exists at least one root between a and b.
206
Then the root lies between a and b, let its approximate value is given by
𝑎+𝑏
𝑥 =
2
If f(x0)=0, x0 is the root of the equation
If f(x0)≠0, x0 is the root of the equation, the root lies between x0 and b or between x0 and a depending
on whether f(x0) is negative or positive
If f(x0) is positive, the root lies between a and x0, then 𝑥 =
If f(x0) is negative, the root lies between b and x0, then 𝑥 =
And the process is repeated until we get the required precision.
1. Find the real root of the equation f(x)= x3-x-1 using bisection method. Carryout computation up to
5th stage
Ans:
𝑓(𝑥) = 𝑥 − 𝑥 − 1
𝑓(0) = 0 − 0 − 1 = −1
𝑓(2) = 8 − 2 − 1 = 6, +ve
a=1; b=2
207
𝑥 +𝑥 1.3125 + 1.375 𝑓(𝑥 ) = 𝑓(1.34375) = (1.34375) −
𝑥 = = = 1.34375
2 2 1.34375 − 1 = 0.0826, +ve
Root lies between 𝑥 and 𝑥
𝑥 +𝑥 1.3125 + 1.34375
𝑥 = =
2 2
= 𝟏. 𝟑𝟐𝟖𝟏𝟐𝟓
The approximate root is 𝟏. 𝟑𝟐𝟖𝟏𝟐𝟓
2. Find a root of the equation 𝑥 − 4𝑥 − 9 = 0 using bisection method correct up to three decimal
places.
208
2.70508 2.707035 𝑥 +𝑥 𝑓(𝑥 ) = −0.008457 -ve
𝑥 =
2
2.70508 + 2.707035
=
2
= 2.706058
Since 𝑓(𝑥 ) is negative replace a by 𝑥
2.706058 2.707035 𝑥 +𝑥 𝑓(𝑥 ) = 0.00021 +ve
𝑥 =
2
2.706058 + 2.707035
=
2
= 2.70654
Since 𝑓(𝑥 ) is positive replace b by 𝑥
2.706058 2.70654 𝑥 +𝑥
𝑥 =
2
2.706058 + 2.70654
= = 𝟐. 𝟕𝟎𝟔𝟐𝟗𝟗
2
Because the three digits after decimal points of 𝑥 and 𝑥 are same, the solution is three
decimal point accurate
The approximate root is 𝟐. 𝟕𝟎𝟔𝟐𝟗𝟗
3. Using the bisection method, find an approximate root of the equation sin(𝑥) = , that lies between
x=1 and x=1.5 (measured in radians). Carry out computation up to 7th stage.
𝑥 sin(𝑥) − 1 = 0
𝑓(𝑥) = 𝑥 sin(𝑥) − 1
Also given a=1 and b=1.5
209
𝒙𝟒 + 𝒙𝟏 𝟏. 𝟏𝟎𝟗𝟑𝟕𝟓 + 𝟏. 𝟏𝟐𝟓 𝑓(𝑥 ) = 𝑓(1.11718) = 0.004237, +ve
𝒙𝟓 = =
𝟐 𝟐
= 𝟏. 𝟏𝟏𝟕𝟏𝟖
Root lies between 𝒙𝟒 and 𝒙𝟓
𝒙𝟒 + 𝒙𝟓
𝒙𝟔 =
𝟐
𝟏. 𝟏𝟎𝟗𝟑𝟕𝟓 + 𝟏. 𝟏𝟏𝟕𝟏𝟖
=
𝟐
= 𝟏. 𝟏𝟏𝟑𝟐𝟕8
Exercise
1. Find the root of the equation cos(𝑥) = 𝑥𝑒 using bisection method up to 6th stage.
[Hint: a=1;b=0; 𝑥 = 0.51562] Ans: Page-42 of NUMERICAL METHODS IN ENGINEERING AND
SCIENCE by B.S. Grewal
2. Find a positive real root of 𝑥𝑙𝑜𝑔 𝑥 = 1.2 using bisection method up to 5th stage.
[𝑓(𝑥) = 𝑥𝑙𝑜𝑔 𝑥 − 1.2; 𝑎 = 2, 𝑏 = 3; 𝑥 = 2.734375] Ans: Page-43 of NUMERICAL
METHODS IN ENGINEERING AND SCIENCE by B.S. Grewal
3. Find a real root of 𝑓(𝑥) = 𝑥 + 𝑥 + 𝑥 + 7 correct to three decimal places.
[Ans: Page-26 of Introductory Methods of Numerical Analysis by S.S. Sastry]
Algorithm
1. Import necessary module numpy
2. Define the given function as f(x)
3. Input a value of x for which the function f(x) is negative and store
it in variable ‘a’
4. Input a value of x for which the function f(x) is positive and stroe
it in variable ‘b’
5. Start an infinite loop using while to repeat the steps from I to V
given below
I. Compute (a+b)/2 and store in x
II. If f(x)=0, print exact root=x, stop the iteration using break
III.elif, if f(x)<0.0001 (accuracy) stop iteration using break
IV. elif, if f(x)>0, replace b with x
V. else, replace a with x
Script file (problem-1)
Program_127.py
1 def f(x):
2 return (x**3-x-1)
3 a=int(input('Enter a value for which f(x) is negative(a):'))
210
4 b=int(input('Enter a value for which f(x) is positive(b):'))
5 while True:
6 x=(a+b)/2
7 print('x=',x)
8 if f(x)==0:
9 print('The exact root is:',x)
10 break
11 elif abs(f(x))<0.001:
12 print('The approximte root is:',x)
13 break
14 elif f(x)>0:
15 b=x #if f(x) is +ve, replace b by x
16 else:
17 a=x #if f(x) is -ve, replace a by x
18
Output
IDLE Shell 3.10.4
>>> Enter a value for which f(x) is negative(a):1
Enter a value for which f(x) is positive(b):2
x= 1.5
x= 1.25
x= 1.375
x= 1.3125
x= 1.34375
x= 1.328125
x= 1.3203125
x= 1.32421875
x= 1.326171875
x= 1.3251953125
x= 1.32470703125
The approximate root is: 1.32470703125
211
15 elif f(x)>0:
16 b=x #if f(x) is +ve, replace b by x
17 else:
18 a=x #if f(x) is -ve, replace a by x
Output
IDLE Shell 3.10.4
>>> Enter a value for which f(x) is negative(a):1
Enter a value for which f(x) is positive(b):1.5
1.25
1.125
1.0625
1.09375
1.109375
1.1171875
1.11328125
1.115234375
1.1142578125
1.11376953125
1.114013671875
1.1141357421875
1.11419677734375
1.114166259765625
1.1141510009765625
The approximte root is: 1.1141510009765625
This method is used to improve the result obtained by other method (bisection method, false position
method) to obtain the root of the algebraic equation. Newton-Raphson has a second-order or
quadratic convergence.
Let x0 be an approximate root of f(x)=0 and let x1=x0+h be the correct root so that f(x1)=0. Expanding
f(x0+h) by Taylor series, we get
ℎ
𝑓(𝑥 + ℎ) = 𝑓(𝑥 ) + ℎ𝑓 (𝑥 ) + ℎ𝑓 (𝑥 ) + ⋯ = 0
2!
Since h is small neglecting h2 and higher powers of h, we get
𝑓(𝑥 ) + ℎ𝑓 (𝑥 ) = 0
𝑓(𝑥 ) = −ℎ𝑓 (𝑥 )
𝑓(𝑥 )
ℎ=−
𝑓 (𝑥 )
Since x1=x0+h, a better approximation than x0 is therefore given by
𝑓(𝑥 )
𝑥 =𝑥 −
𝑓 (𝑥 )
Similarly starting with x1, a still better approximation x2 is given by
212
𝑓(𝑥 )
𝑥 =𝑥 −
𝑓 (𝑥 )
Ans:
Given 𝑥 − 𝑥 = 10
𝑓(𝑥) = 𝑥 − 𝑥 − 10
𝑓(0) = 0 − 0 − 10 = −10
𝑓(1) = 1 − 1 − 10 = −10, -ve
𝑓(2) = 16 − 2 − 10 = 4, +ve
Root lies between 1 & 2, since 𝑓(2) is closer to zero than 𝑓(1), 𝑥 can be taken as 𝑥 = 2
We have
𝑓(𝑥) = 𝑥 − 𝑥 − 10
𝑓 (𝑥) = 4𝑥 − 1
𝑥 =2
( ) 𝑓(𝑥 ) = 𝑓(2) = 2 − 2 − 10 = 4
𝒙𝟏 = 𝑥 − ( )
=2− = 𝟏. 𝟖𝟕𝟏
𝑓 (𝑥 ) = 𝑓 (2) = 4 × 2 − 1 = 31
( ) . 𝑓(𝑥 ) = 𝑓(1.871) = 1.871 − 1.871 − 10 =
𝒙𝟐 = 𝑥 − ( )
= 1.871 − .
=
0.383487
𝟏. 𝟖𝟓𝟓𝟖
𝑓 (𝑥 ) = 𝑓 (1.871) = 4 × 1.871 − 1 = 25.24081
( ) 𝑓(𝑥 ) = 𝑓(1.8558 ) = 1.8558 − 1.8558 − 10 =
𝒙𝟑 = 𝑥 − ( )
= 1.8558 −
.
0.005292
= 𝟏. 𝟖𝟓𝟓𝟓𝟖 𝑓 (𝑥 ) = 𝑓 (1.8558 ) = 4 × 1.8558 − 1 =
.
24.565453
2. Find by Newton’s method, the real root of equation 3𝑥 = cos 𝑥 + 1, correct up to four decimal
places.
Ans:
𝑓(𝑥) = 3𝑥 − 𝑐𝑜𝑠𝑥 − 1
𝑓(0) = 0 − cos(0) − 1 = −2 , -ve
213
𝑓(1) = 3 − cos(1 × 57.3) − 1 = 3 − 0.5402 − 1 = 1.4598, +𝑣𝑒
The root lies between 0 & 1. Here 𝑓(1) is closer to zero than 𝑓(0), hence 𝑥 = 1
We have
𝑓(𝑥) = 3𝑥 − 𝑐𝑜𝑠𝑥 − 1
𝑓 (𝑥) = 3 + sin 𝑥
𝑥 =1
( ) . 𝑓(𝑥 ) = 𝑓(1) = 3 × 1 − cos (57.3) − 1 = 1.4598
𝒙𝟏 = 𝑥 − ( )
=1− .
=
𝑓 (𝑥 ) = 𝑓 (1) = 3 + sin(57.3) = 3.84151
𝟎. 𝟔𝟐𝟎𝟎𝟐
( ) 𝑓(𝑥 ) = 𝑓(0.62002) = 3 × 0.62002 −
𝒙𝟐 = 𝑥 − ( )
= 0.62002 −
.
cos (0.62002 × 57.3) − 1 = 0.04632
.
= 𝟎. 𝟔𝟎𝟕𝟏𝟏𝟒 𝑓 (𝑥 ) = 𝑓 (0.62002) = 3 + sin(0.62002 × 57.3) =
3.58108
( ) 𝑓(𝑥 ) = 𝑓(0.607114 ) = 0.000072
𝒙𝟑 = 𝑥 − ( )
= 0.607114 −
.
𝑓 (𝑥 ) = 𝑓 (0.607114 ) = 3.570536
.
= 𝟎. 𝟔𝟎𝟕𝟎𝟗~ 𝟎. 𝟔𝟎𝟕𝟏
3. Using Newton’s iteration method, find the real root of 𝑥𝑙𝑜𝑔 𝑥 = 1.2 correct to five decimal points
Ans:
𝑥𝑙 𝑥 = 1.2
𝑓(𝑥) = 𝑥𝑙𝑜𝑔 𝑥 − 1.2
𝑓 (𝑥) = 𝑑(𝑥𝑙𝑜𝑔 𝑥 − 1.2) = 𝑙𝑜𝑔 𝑥 + 𝑥 𝑑(𝑙𝑜𝑔 𝑥)= 𝑙𝑜𝑔 𝑥 + 𝑥 𝑑(𝑙𝑜𝑔 𝑒 𝑙𝑜𝑔 𝑥 )
= 𝑙𝑜𝑔 𝑥 + 0.43429 × 𝑥
= 𝑙𝑜𝑔 𝑥 + 0.43429
𝑓(0) = 0 × 𝑙𝑜𝑔 0 − 1.2 = −1.2
𝑓(1) = 1 × 𝑙𝑜𝑔 1 − 1.2 = −1.2 (since log 1=0)
𝑥 =2
( ) . 𝑓(𝑥 ) = 𝑓(2) = 2 × 𝑙𝑜𝑔 2 − 1.2=-0.59794
𝒙𝟏 = 𝑥 − ( )
=2+ .
=
𝑓 (𝑥 ) = 𝑙𝑜𝑔 2 + 0.43429 = 0.735319
𝟐. 𝟖𝟏𝟑𝟏𝟕
214
( ) 𝑓(𝑥 ) = 𝑓(2.81317 ) = 2.81317 × 𝑙𝑜𝑔 2.81317 −
𝒙𝟐 = 𝑥 − ( )
= 2.81317 −
.
1.2=0.06366
.
= 𝟐. 𝟕𝟒𝟏𝟏𝟏𝟓 𝑓 (𝑥 ) = 𝑓 (2.81317) = 𝑙𝑜𝑔 2.81317 + 0.43429 =
0.88348
( ) 𝑓(𝑥 ) = 𝑓(2.741115 ) = 2.741115 ×
𝒙𝟑 = 𝑥 − ( )
= 2.741115 −
.
𝑙𝑜𝑔 2.741115 − 1.2=0.0004089
.
= 𝟐. 𝟕𝟒𝟎𝟔𝟒𝟔𝟐 𝑓 (𝑥 ) = 𝑓 (2.741115 ) = 𝑙𝑜𝑔 2.741115 +
0.43429 = 0.872217
( ) 𝑓(𝑥 ) = 𝑓(2.7406462 ) = 2.7406462 ×
𝒙𝟒 = 𝑥 − ( )
= 2.7406462 +
.
𝑙𝑜𝑔 2.7406462 − 1.2=-0.0001
.
= 𝟐. 𝟕𝟒𝟎𝟔𝟓𝟕 𝑓 (𝑥 ) = 𝑓 (2.7406462 ) = 𝑙𝑜𝑔 2.7406462 +
0.43429 = 0.8721429
( ) 𝑓(𝑥 ) = 𝑓(2.740657 ) = 2.740657 ×
𝒙𝟓 = 𝑥 − ( )
= 2.740657 −
.
𝑙𝑜𝑔 2.740657 − 1.2=0.0000064449
.
= 𝟐. 𝟕𝟒𝟎𝟔𝟓𝟖 𝑓 (𝑥 ) = 𝑓 (2.740657 ) = 𝑙𝑜𝑔 2.740657 +
0.43429 = 0.8721446
4. Using Newton-Raphson method, find a real root, correct to 3 decimal places of the equation
sin 𝑥 = gives that the root lies between 𝜋/2 and 𝜋.
Ans:
𝑓(𝑥) = sin 𝑥 −
𝑓 (𝑥) = cos 𝑥 −
Choosing 𝑥 = 𝜋/2
/
𝒙𝟏 = 𝑥 −
( )
= − = + 𝑓(𝑥 ) = 𝑓(𝜋/2 ) = sin 𝑥 − = sin − =1 −
( )
( ) 𝑓 (𝑥 ) = cos 𝑥 − = cos − = −
= +2− =𝟐
( ) .
𝒙𝟐 = 𝑥 − = 2− = 𝑓(𝑥 ) = 𝑓(2 ) = sin(2 × 57.3) − = sin 114.6 − 1 =
( ) .
2 − 0.09906 = 1.90094 0.90923 − 1 = −0.09077
𝑓 (𝑥 ) = 𝑓 (2) = cos(2 × 57.3) − = cos(114.6) −
= -0.91628
( ) 𝑓(𝑥 ) = 𝑓(1.90094 ) = sin(1.90094 × 57.3) −
𝒙𝟑 = 𝑥 − ( )
= 1.90094 −
.
. = 0.9459503 − 0.95047 = −0.004567
.
= 𝟏. 𝟖𝟗𝟓𝟑𝟗𝟗
𝑓 (𝑥 ) = 𝑓 (1.90094) = cos(1.90094 × 57.3) − = -
0.32431-0.5=-0.824311
215
( ) 𝑓(𝑥 ) = 𝑓(1.895399 ) = sin(1.895399 × 57.3) −
𝒙𝟒 = 𝑥 − ( )
= 1.895399 +
. = 0.947735 − 0.9476995 = 0.0000355
.
= 𝟏. 𝟖𝟗𝟓𝟒𝟒𝟐𝟑
𝑓 (𝑥 ) = 𝑓 (1.895399 ) = −0.319064 − 0.5 =
0.0000355
( ) 𝑓(𝑥 ) = 𝑓(1.8954423 ) = sin(1.8954423 ×
𝒙𝟓 = 𝑥 − ( )
= 1.8954423 −
. 57.3) − = 0.9477199 − 0.94772 = −0.0001
.
= 𝟏. 𝟖𝟗𝟓𝟒𝟐
𝑓 (𝑥 ) = 𝑓 (1.8954423 ) = cos(1.8954423 ×
57.3) − = -0.8191034
Algorithm
1. Import necessary module
2. Define the given function as f(x)
3. Define a function df(x) to evaluate the derivative of the given
function
4. Input an approximate solution and store it in variable ‘x’
5. Start an infinite loop using while to repeat the steps from I to III
given below
( ) ( )
I. Calculate the correction of the solution ℎ = ( )
= ( )
216
>>> Enter an approximate root of the equation:2
1.870967741935484
1.8557807016967116
1.8555845610108843
The approximate root is: 1.8555845610108843
217
12 print(x)
13 print('The approximate root is:',x)
Output
IDLE Shell 3.10.4
>>> Enter an approximate root of the equation,x0=:pi/2
1.5707963267948966
2.0
1.900995594203909
1.8955116453795946
The approximate root is: 1.8955116453795946
In experiment we often have to fit a curve to data which are subject to error. The strategy for such a
case is to derive an approximate function that broadly fits the data without necessarily passing
through the given points. The curve is drawn such that the discrepancy between the data points and
the curve is least. In the method of least squares, the sum of the square of the error is minimum.
218
Fig: Experimental data(square) and fitted data (circle)(straight line, 𝑓(𝑥) = 𝑌 = 𝑎 + 𝑎 𝑥). e1,e2,…e5
are the error between actual data and fitted data.
Let the set of data points be (xi,yi), i=1,2,….,n and let the curve is given by Y=f(x) be fitted to this data.
At x=x1, the given ordinate is y1 and the corresponding values on the fitting curve is f(xi)
If ei is the error of approximation at x=xi then we have
𝑒=𝑦 −𝑌
𝑒 = 𝑦 − 𝑓(𝑥 )
Consider the whole n number of data points, then
𝑆 = (𝑦 − 𝑌 ) + (𝑦 − 𝑌 ) + ⋯ + (𝑦 − 𝑌 ) ………………(1)
= (𝑦 − 𝑓(𝑥 )) + (𝑦 − 𝑓(𝑥 )) + ⋯ + (𝑦 − 𝑓(𝑥 ))
𝑆 = 𝑒 +𝑒 …+𝑒
Then the method of least square consist in minimizing S, i,e. sum of squares of the error
Fitting a straight line
Equation of a straight line from the equation of polynomial is given by
𝑌 = 𝑎 + 𝑎 𝑥 ………………….. (2)
Sub equ (2) in equ (1)
𝑆 = (𝑦 − (𝑎 + 𝑎 𝑥 )) + (𝑦 − (𝑎 + 𝑎 𝑥 )) + ⋯ + (𝑦 − (𝑎 + 𝑎 𝑥 )) …….. (3)
For s to be minimum
𝜕𝑆 𝜕𝑆
= 0 𝑎𝑛𝑑 =0
𝜕𝑎 𝜕𝑎
𝜕𝑆
= −2[𝑦 − (𝑎 + 𝑎 𝑥 )] − 2[𝑦 − (𝑎 + 𝑎 𝑥 )] − ⋯ − 2[𝑦 − (𝑎 + 𝑎 𝑥 )] = 0
𝜕𝑎
Cancel all the 2s and on rearranging.
𝑛𝑎 + 𝑎 [𝑥 + 𝑥 + ⋯ + 𝑥 ] = 𝑦 + 𝑦 + ⋯ + 𝑦
More compactly
𝒏𝒂𝟎 + 𝒂𝟏 ∑ 𝒙 = ∑ 𝒚 …………….(4)
similarly
𝜕𝑆
= −2𝑥 [𝑦 − (𝑎 + 𝑎 𝑥 )] − 2𝑥 [𝑦 − (𝑎 + 𝑎 𝑥 )] − ⋯ − 2𝑥 [𝑦 − (𝑎 + 𝑎 𝑥 )] = 0
𝜕𝑎
On rearranging
𝑎 [𝑥 + 𝑥 + ⋯ + 𝑥 ] + 𝑎 [𝑥 + 𝑥 + ⋯ + 𝑥 ] = 𝑥 𝑦 + 𝑥 𝑦 + ⋯ + 𝑥 𝑦
𝒂𝟎 ∑ 𝒙 + 𝒂𝟏 ∑ 𝒙𝟐 = ∑ 𝒙𝒚 …………….(5)
Equ (4) and (5) is called normal equations. To find a0 and a1 , we have to solve equ (4) and (5). Multiply
equ (4) by ∑ 𝑥 and divide by n
219
𝑛𝑎 + 𝑎 ∑ 𝑥 = ∑ 𝑦 …………….(4)
𝑎 ∑ 𝑥 + 𝑎 ∑ 𝑥 = ∑ 𝑥𝑦 …………….(5)
𝑎 ∑ 𝑥 + 𝑎 ∑ 𝑥 = ∑ 𝑥𝑦 …………….(5)
Subtract equ (6) from (5)
𝑎 1
𝑎 𝑥 − ( 𝑥) = 𝑥 − 𝑥 𝑦
𝑛 𝑛
1
∑ 𝑥𝑦 − ∑ 𝑥 ∑ 𝑦
𝑎 = 𝑛
1
∑ 𝑥 − (∑ 𝑥)
𝑛
𝒏 ∑ 𝒙𝒚 − ∑ 𝒙 ∑ 𝒚
𝒂𝟏 =
𝒏 ∑ 𝒙𝟐 − (∑ 𝒙)𝟐
From equ(4)
𝑛𝑎 = 𝑦−𝑎 𝑥
∑𝒚 ∑𝒙
𝒂𝟎 = − 𝒂𝟏
𝒏 𝒏
𝒂𝟎 = 𝒚 − 𝒂𝟏 𝒙
Sometime a goodness of fit is adopted which is estimated in terms of correlation coefficient (cc)
defined by
𝑆 −𝑆
𝑐𝑐 =
𝑆
Where 𝑆 = ∑ (𝑦 − 𝑦)
1. Find the best values of a0 and a1 if the straight line Y=a0+a1x is fitted to the data (xi,yi) given by
(1,0.6), (2,2.4), (3,3.5) , (4,4.8), (5,5.7). Also find the correlation coefficient.
Ans: From the principle of least square, we have the following equations for the straight line to be
fitted.
𝒏 ∑ 𝒙𝒚 ∑ 𝒙 ∑ 𝒚
𝒂𝟏 = 𝒏 ∑ 𝒙𝟐 (∑ 𝒙)𝟐
;
𝒂𝟎 = 𝒚 − 𝒂𝟏 𝒙
220
𝒙 𝒚 𝒙𝟐 𝒙𝒚
1 0.6 1 0.6
2 2.4 4 4.8
3 3.5 9 10.5
4 4.8 16 19.2
5 5.7 25 28.5
∑ 𝒙=15 ∑ 𝒚=17 ∑ 𝒙𝟐 =55 ∑ 𝒙𝒚=63.6
(∑ 𝒙)𝟐 =225
𝒙 = 15/5 =3 𝒚 = 17/5 =3.4
2. Certain experimental values of x and y are given below (0,-1), (2,5), (5,12), (7,20). If a straight-line
Y=a0+ a1 x is fitted to the observed data, find the approximate values of a0 and a1.
Ans: From the principle of least square, we have the following equations for the straight line to be
fitted
𝒏 ∑ 𝒙𝒚 ∑ 𝒙 ∑ 𝒚
𝒂𝟏 = 𝒏 ∑ 𝒙𝟐 (∑ 𝒙)𝟐
;
𝒂𝟎 = 𝒚 − 𝒂𝟏 𝒙
And the equation of the straight line is given by
𝑌 =𝑎 +𝑎 𝑥
𝒙 𝒚 𝒙𝟐 𝒙𝒚
0 -1 0 0
2 5 4 10
5 12 25 60
7 20 49 140
∑ 𝒙=14 ∑ 𝒚=36 ∑ 𝒙𝟐 =78 ∑ 𝒙𝒚=210
(∑ 𝒙)𝟐 =196
𝒙 = 14/4 =3.5 𝒚 = 36/4 =9
221
𝑛 ∑ 𝑥𝑦 − ∑ 𝑥 ∑ 𝑦 4 × 210 − 14 × 36 840 − 504 336
𝒂𝟏 = = = = = 𝟐. 𝟖𝟗
𝑛 ∑ 𝑥 − (∑ 𝑥) 4 × 78 − 196 312 − 196 116
𝒂𝟎 = 𝑦 − 𝑎 𝑥̅ = 9 − 2.89 × 3.5 = −𝟏. 𝟏𝟏𝟓
3. Fit a straight line to the following data and write a program using python.
x 6 7 7 8 8 8 9 9 10
y 5 5 4 5 4 3 4 3 3
Ans: From the principle of least square, we have the following equations for the straight line to be
fitted.
𝒏 ∑ 𝒙𝒚 ∑ 𝒙 ∑ 𝒚
𝒂𝟏 = 𝒏 ∑ 𝒙𝟐 (∑ 𝒙)𝟐
;
𝒂𝟎 = 𝒚 − 𝒂𝟏 𝒙
And the equation of the straight line is given by
𝑌 =𝑎 +𝑎 𝑥
𝒙 𝒚 𝒙𝟐 𝒙𝒚
6 5 36 30
7 5 49 35
7 4 49 28
8 5 64 40
8 4 64 32
8 3 64 24
9 4 81 36
9 3 81 27
10 3 100 30
∑ 𝒙=72 ∑ 𝒚=36 ∑ 𝒙𝟐 =588 ∑ 𝒙𝒚=282
(∑ 𝒙)𝟐 =5184
𝒙 = 72/9 =8 𝒚 = 36/9 =4
𝒀 = 𝟖 − 𝟎. 𝟓𝒙
4. By the method of least square, find the straight line that best fits the following data
x 1 2 3 4 5
y 14 27 40 50 68
222
Ans: From the principle of least square, we have the following equations for the straight line to be
fitted.
𝒏 ∑ 𝒙𝒚 ∑ 𝒙 ∑ 𝒚
𝒂𝟏 = 𝒏 ∑ 𝒙𝟐 (∑ 𝒙)𝟐
;
𝒂𝟎 = 𝒚 − 𝒂𝟏 𝒙
And the equation of the straight line is given by
𝑌 =𝑎 +𝑎 𝑥
𝒙 𝒚 𝒙𝟐 𝒙𝒚
1 1427 1 14
2 40 4 54
3 55 9 120
4 68 16 220
5 25 340
∑ 𝒙=15 ∑ 𝒚=204 ∑ 𝒙𝟐 =55 ∑ 𝒙𝒚=784
(∑ 𝒙)𝟐 =225
𝒙 = 15/5 =3 𝒚 = 204/5
=40.8
𝒀 = 𝟏𝟑. 𝟔𝒙
Algorithm
6. Import necessary modules numpy and matplotlib or pylab.
7. Enter the number of data points.
8. Enter the x and y data sets and store it in two list a and b
respectively.
9. Convert list a and b in to array x and y respectively.
∑ ∑ ∑
10. Calculate the slope of the straight line 𝒂𝟏 = ∑ (∑ )
11. Print 𝒂𝟏
12. Calculate the y intercept 𝒂𝟎 = 𝑦 − 𝑎 𝑥̅
13. Print 𝒂𝟎
14. Print the equation of the straight line 𝑌 = 𝑎 + 𝑎 𝑥
10.Plot the given x & y data
223
11.Plot the straight line, x & Y
12.Label x axis as ‘x’
13.Label y axis as ‘y’
14.Add title ‘Curve fitting: straight line fitting, Principle of least
squares’
15.Add legends
16.Display the plot
Script file
Program_132.py
1 import matplotlib.pyplot as plt
2 import numpy as np
3 a=[]
4 b=[]
5 n=int(input('Enter the number of data set,n='))
6 for i in range(n):
7 xdata=float(input('Enter x data:'))
8 ydata=float(input('Enter y data:'))
9 a.append(xdata)
10 b.append(ydata)
11 x=np.array(a)
12 y=np.array(b)
13 a1=(n*np.sum(x*y)-(np.sum(x)*np.sum(y)))/(((n*np.sum(x**2))-
14 (np.sum(x)**2)))
15 print('a1=',a1)
16 a0=(np.sum(y)/n)-(a1*(np.sum(x)/n))
17 print('a0=',a0)
18 Y=a0+x*a1
19 print('Y=',Y)
20 print('Y=',a0,'+',a1,'*x')
21 plt.plot(x,y,'r*-')
22 plt.plot(x,Y,'bo-')
23 plt.xlabel('x',fontsize=18)
24 plt.ylabel('y',fontsize=18)
25 plt.legend(['exp data','Fit'])
26 plt.title('Curve fitting:Straight line fitting\nMethod of least
27 squares',fontsize=20)
28 plt.grid()
29 plt.show()
Output
IDLE Shell 3.10.4
>>> Enter the number of data set,n=5
Enter x data:1
Enter y data:14
Enter x data:2
Enter y data:27
Enter x data:3
224
Enter y data:40
Enter x data:4
Enter y data:55
Enter x data:5
Enter y data:68
x= [1. 2. 3. 4. 5.]
y= [14. 27. 40. 55. 68.]
a1= 13.6
a0= 0.0
Y= [13.6 27.2 40.8 54.4 68. ]
Y= 0.0 + 13.6 *x
Output
3.5 Interpolation
• Finite difference
• Forward difference
• Forward difference table
• Newtons forward interpolation formula
Interpolation
Suppose we are given the following values of y=f(x) for a set of values of x
X: x0 x1 x2 ……………… xn
225
Y: y0 y1 y2 ……………… yn
The process of finding the value of y corresponding to any given value of x=x i between x0 and xn is
called interpolation. Thus, interpolation is the technique of estimating the value of a function for any
intermediate values of the independent variable. Similarly, the process of finding the value of the
function outside the given range is called extrapolation. The term interpolation however taken to
include extrapolation
If the function f(x) is known explicitly, then the value of y corresponding to any value of x can be easily
found (for example f(x)=y=mx+c, for any value of x, y can be estimated from the function). On the
other hand, if the form of f(x) is not known, it is difficult to determine the exact form of f(x) with the
help of tabulated set of values (xi,yi).
In such case, f(x) is replaced by simpler function ф(x) which assumes the same values as those of f(x)
at the tabulated set of points. Another values may be calculated from ф(x) which is known as known as
interpolating function or smoothing function. If ф(x) is a polynomial, then it is called interpolating
polynomial, then the process is called polynomial interpolation.
Assume that we have a table of values (xi,yi), i=1,2,….,n of any function y=f(x), the values of x being
equally spaced xi=x0+ih, i=0,1,2…..,n. Suppose that we are required to recover the values of f(x) for
some intermediate value of x, or to obtain the derivative of f(x) for some x in the range x 0<=xi<=xn. The
method for the solution to these problems are based on the concepts of ‘difference’ of a function which
we now proceed to define. Finite difference are of three type
• Forward difference
• Central difference
• Backward difference
Here we consider only the forward difference method
If y0, y1,….,yn denotes a set of values of y, then y1-y0, y2-y1,……..,yn-yn-1 are called the difference of y.
Denoting these difference by Δy0, Δy1, Δy2,……, Δyn-1 respectively. Here Δ is called forward difference
operator. Δy0, Δy1, Δy2,…… are called first forward differences. The differences of first forward
differences are called second forward difference and are denoted by Δ2y0, Δ2y1, Δ3y2,……. Similarly
we can define the third forward difference, fourth forward difference and so on.
226
3.5.3 Forward difference table
x y 2 3 4 5 6
Δ y0= y1- y0
Δ2 y0= Δ y1- Δ y0
= y2- y1- y1- y0
= y2- 2y1- y0
Δ3 y0= Δ2 y1 - Δ2 y0
=Δ y2- Δ y1- Δ y1+ Δ y0
= Δ y2- 2Δ y1+ Δ y0
= y3- y2- 2y2+ 2y1+ y1- y0
= y3- 3y2 +3y1+ y0
Δ4 y0= Δ3 y1- Δ3 y0
=Δ2 y2- Δ2 y1- Δ2 y1+ Δ2 y0
= Δ y2 -2Δ y1+ Δ y0
2 2 2
Let the function y=f(x) take the values y0,y1,……,yn corresponding to the value x0,x1,……,xn of x. Let
these values of x be equi-spaced such that xi=x0 +ih, where i=0,1,2,3….n. Or for any value of x can be
written as x=x0-ph. Therefore 𝑝 =
Assuming y(x) to be a polynomial of the nth degree in x such that y(x0)=y0, y(x1)=y1,…….., y(xn)=yn
227
We can write
𝑦(𝑥) = 𝑎 + 𝑎 (𝑥 − 𝑥 ) + 𝑎 (𝑥 − 𝑥 )(𝑥 − 𝑥 ) + 𝑎 (𝑥 − 𝑥 )(𝑥 − 𝑥 )(𝑥 − 𝑥 ) + ⋯ +
𝑎 (𝑥 − 𝑥 )(𝑥 − 𝑥 ) … . . (𝑥 − 𝑥 ) ………..(1)
Putting x=x0, x1,….,xn successively in equ (1), we get
y0=a0 ….. (2)
y1=a0+a1(x1-x0) ….. (3)
y2=a0+a1(x2-x0)+a2(x2-x0)(x2-x1) ….. (4)
and so on
From these, we get
From equ (2), a0= y0 ……….(5)
Sub a0 in equ (3)
y1=y0+a1(x1-x0)
∆
𝑎 = = ∆𝑦 …………. (7)
∆ ∆ ∆
𝑎 = = = !
∆ 𝑦
Similarly
𝑎 = !
∆ 𝑦
𝑦(𝑥) = 𝑦 + ∆𝑦 (𝑥 − 𝑥 ) + !
∆ 𝑦 (𝑥 − 𝑥 )(𝑥 − 𝑥 ) + !
∆ 𝑦 (𝑥 − 𝑥 )(𝑥 − 𝑥 )(𝑥 − 𝑥 )+. ..
228
x-x2=x-x1-(x2-x1)=(p-1)h-h=(p-2)h
sub in the above equation
𝒑(𝒑 − 𝟏) 𝟐 𝒑(𝒑 − 𝟏)(𝒑 − 𝟐) 𝟑
𝒚𝒑 = 𝒚𝟎 + 𝒑∆𝒚𝟎 + ∆ 𝒚𝟎 + ∆ 𝒚𝟎 +. ..
𝟐! 𝟑!
1. The table gives the distance in nautical mile of the visible horizon for the given heights in feet above
the earth’s surface
Ans:
x y Δ Δ2 Δ3 Δ4
100 10.63
2.40
150 13.03 -0.39
2.01 0.15
200 =x0 15.04= y0 -0.24 -0.07
x=218 1.77=Δ y0 0.08
250 16.81 -0.16 =Δ2 y0 -0.05
1.61 0.03=Δ3 y0
300 18.42 -0.13 -0.01= Δ4 y0
1.48 0.02
350 19.90 -0.11
1.37
400 21.27
ℎ = 𝑥 − 𝑥 = 50
𝑝= = = 0.36
229
( ) ( )( ) ( )( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦 + ∆ 𝑦 +. ..
! ! !
. ( . ) . ( . )( . )
𝑦 = 15.04 + 0.36 × 1.77 + (−0.16) + (0.03) +
. ( . )( . )( . )
(−0.01)
( . )( . ) . ( . )( . )
𝑦 = 15.04 + 0.637 + (−0.16) + (0.03) +
. ( . )( . )( . )
(−0.01)
2. From the following table, estimate the number of students who obtained marks between 40 and 45
x y Δ Δ2 Δ3 Δ4
40=x0 31=y0
x=45 42=Δ y0
50 73 9=Δ2 y0
51 -25= Δ3y0
60 =x0 124 -16 37= Δ4y0
35 12
70 159 -4
31
80 190
ℎ = 𝑥 − 𝑥 = 10
𝑝= = = 0.5
230
Newtons forward interpolation formula is given by
( ) ( )( ) ( )( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦 + ∆ 𝑦 +. ..
! ! !
. ( . ) . ( . )( . ) . ( . )( . )( . )
𝑦 = 31 + 0.5 × 42 + (9) + (−25) + (37)+. ..
! ! !
. ( . ) . ( . )( . ) . ( . )( . )( . )
𝑦 = 31 + 21 + (9) + (−25) + (37)
𝑦 = 47.87~𝟒𝟖 students
Therefore, the number of students with marks less than 45 is 48. Hence the number of
students got marks between 40-45 is 48-31=17
x 0 1 2 3
y 1 2 1 10
𝑝= =𝑥
231
( ) ( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦
! !
Upon substituting
( ) ( )( )
𝑦 =1+𝑥×1+ (−2) + (12)
𝑦 = 1 + 𝑥 − 𝑥 + 𝑥 + 2𝑥 − 4𝑥 − 2𝑥 + 4𝑥
𝑦 = 2𝑥 − 7𝑥 + 6𝑥 + 1
4.Find the first and second term of the series of the table given below
x 3 4 5 6 7 8 9
y 4.8 8.4 14.5 23.6 36.2 52.8 73.9
Ans: Here we have to find y(1) and y(2). The difference table is given by
x y Δ Δ2 Δ3 Δ4
3=x0 4.8=y0
3.6= Δy0
4 8.4 2.5= Δ2y0
6.1 0.5== Δ3y0
5 14.5 3 0= Δ4y0
9.1 0.5
6 23.6 3.5 0
12.6 0.5
7 36.2 4 0
16.6 0.5
8 52.8 4.5
21.1
9 73.9
232
( ) ( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦
! !
Upon substituting
( )( ) ( )( )( )
𝑦 = 4.8 + (−2) × 3.6 + (2.5) + (0.5) = 3.1
( ) ( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦
! !
Upon substituting
( )( ) ( )( )( )
𝑦 = 4.8 + (−1) × 3.6 + (2.5) + (0.5) = 3.1 = 3.2
𝑦(1) = 24
𝑦(3) = 120
𝑦(5) = 336
𝑦(7) = 720
And obtain the value of 𝑦(8)
Ans: The difference table is given by
x y Δ Δ2 Δ3
1=x0 24=y0
96= Δy0
3 120 120 Δ2y0
216 48= Δ3y0
5 336 168
384
7 720
ℎ =𝑥 −𝑥 =2
233
𝑝=
( ) ( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦
! !
Upon substituting
( )( ) ( )( )( )
𝑦 = 24 + × 96 + (120) + (48)
𝑦 = 𝑥 + 6𝑥 + 11𝑥 + 6
To determine 𝑦(8)
Sub x=8, in the above equation
𝑦(8) = 8 + 6 × 8 + 11 × 8 + 6 = 𝟗𝟗𝟎
234
= 3(𝑛 + 2𝑛 + 1) + 9𝑛 + 9 + 7 − 3𝑛 − 9𝑛 − 7
= 6𝑛 + 9𝑛 − 9𝑛 + 3 + 9 + 7 − 7
= 6𝑛 + 12
∆ 𝑆 =∆ 𝑆 −∆ 𝑆
= 6(𝑛 + 1) + 12 − 6𝑛 − 12
=6
∆ 𝑆 =∆ 𝑆 −∆ 𝑆
So we have
∆𝑆 = (𝑛 + 1) ∆𝑆 = (1 + 1) = 8
∆ 𝑆 = 3𝑛 + 9𝑛 + 7 ∆ 𝑆 = 3 + 9 + 7 = 19
∆ 𝑆 = 6𝑛 + 12 ∆ 𝑆 = 6 + 12 = 18
∆ 𝑆 =6 ∆ 𝑆 =6
Newtons interpolation formula can be written as
( ) ( )( )
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦
! !
Similarly if your first term start from 𝑦 , all p will be p-1
( )( ) ( )( )( )
𝑦 = 𝑦 + (𝑝 − 1)∆𝑦 + ∆ 𝑦 + ∆ 𝑦 +−−−
! !
In terms of S and n
( )( ) ( )( )( )
𝑆 = 𝑆 + (𝑛 − 1)∆𝑆 + ∆ 𝑆 + ∆ 𝑆 +
! !
( )( )( )( )
∆ 𝑆 +−−−
!
(𝑛 − 1)(𝑛 − 2) (𝑛 − 1)(𝑛 − 2)(𝑛 − 3)
= 1 + 8(𝑛 − 1) + 19 + 18
2! 3!
(𝑛 − 1)(𝑛 − 2)(𝑛 − 3)(𝑛 − 4)
+ 6+−−−
4!
19 1
= 1 + 8𝑛 − 8 − [𝑛 − 2𝑛 − 𝑛 + 2] + 3(𝑛 − 1)[𝑛 − 3𝑛 − 2𝑛 + 6] + [𝑛 − 2𝑛 − 2
2 4
+ 2][𝑛 − 4𝑛 − 3𝑛 + 12]
= 𝑛 + 𝑛 + 𝑛
( )
=
• First differential
• Second differential
Consider the function y=f(x), which is tabulated for the values x i (=x0+ph), i=0,1,2,……
Derivatives using Newtons-forward difference formula
Newtons forward interpolation formula is given by
𝑝(𝑝 − 1) 𝑝(𝑝 − 1)(𝑝 − 2) 𝑝(𝑝 − 1)(𝑝 − 2)(𝑝 − 3)
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦 + ∆ 𝑦 +⋯
2! 3! 4!
𝑝 −𝑝 𝑝 − 3𝑝 + 2𝑝 𝑝 − 6𝑝 + 11𝑝 − 6𝑝
𝑦 = 𝑦 + 𝑝∆𝑦 + ∆ 𝑦 + ∆ 𝑦 + ∆ 𝑦 +⋯
2! 6 24
Differentiating both sides w.r.t p
235
= ∆𝑦 + !
∆ 𝑦 + ∆ 𝑦 + ∆ 𝑦 +⋯ ………………(1)
𝑝= …………………………(2)
Differentiate p w.r.t. x
= …………………………(3)
𝑑 𝑦 1 2 6𝑝 − 6 12𝑝 − 36𝑝 + 22 1
= [ ∆ 𝑦 + ∆ 𝑦 + ∆ 𝑦 +⋯]
𝑑𝑥 ℎ 2 6 24 ℎ
Put p=0, we obtain
𝒅𝟐 𝒚 𝟏 𝟏𝟏 𝟒 𝟓 𝟏𝟑𝟕 𝟔
( )𝒙𝟎 = [ ∆𝟐 𝒚𝒐 − ∆𝟑 𝒚𝒐 + ∆ 𝒚𝒐 − ∆𝟓 𝒚𝒐 + ∆ 𝒚𝒐 − ⋯ ]
𝒅𝒙𝟐 𝒉𝟐 𝟏𝟐 𝟔 𝟏𝟖𝟎
This is the expression for the second differential.
1. Given that
x 1.0 1.1 1.2 1.3 1.4 1.5 1.6
y 7.989 8.403 8.781 9.129 9.451 9.750 10.031
x y Δ Δ2 Δ3 Δ4 Δ5 Δ6
1.0 7.989
0.414
1.1=𝒙𝟎 8.403=𝒚𝟎 -0.036
0.378=Δ𝒚𝟎 0.006
-
1.2 8.781 -0.002
0.030=Δ2𝒚𝟎
0.348 0.004=Δ3𝒚𝟎 0.001
1.3 9.129 -0.026 0.001=Δ 𝒚𝟎
4 0.002
0.322 0.003 0.003=Δ5𝒚𝟎
236
1.4 9.451 -0.023 0.002
0.299 0.005
1.5 9.750 -0.018
0.281
1.6 10.031
( ) . = [∆𝑦 − ∆ 𝑦 + ∆ 𝑦 − ∆ 𝑦 + ∆ 𝑦]
ℎ = 𝑥 − 𝑥 = 0.1
𝑥 = 1.1; 𝑦 = 8.403
( ) . = .
[0.378 − (−0.03) + (0.004) − (−0.001) + (0.003)]
𝒅𝒚
(𝒅𝒙)𝟏.𝟏 = [0.378 + 0.015 + 0.00133 + 0.00025 + 0.0006 − 0.00033] = 𝟑. 𝟗𝟓𝟐
.
𝒅𝟐 𝒚 11 5
( ) = (−0.03) − 0.004 + (−0.001) − (0.003) = −𝟑. 𝟕𝟒𝟏𝟔
𝒅𝒙𝟐 𝟏.𝟏 ( . ) 12 6
2. From the following table of values of x and y, obtain dy/dx and d2y/dx2 for x=1.2
x 1.0 1.2 1.4 1.6 1.8 2.0 2.2
y 2.7183 3.3201 4.0552 4.9530 6.0496 7.3891 9.0250
x y Δ Δ2 Δ3 Δ4 Δ5 Δ6
1.0 2.7183
0.6018
1.2= 𝒙𝟎 3.3201=𝒚𝟎 0.1333
0.7351= 0.0294
Δ𝒚 𝟎
1.4 4.0552 0.1627= 0.0067
Δ2𝒚𝟎
0.8978 0.0361 0.0013
=Δ3𝒚𝟎
1.6 4.9530 0.1988 0.0080 0.0001
=Δ4𝒚𝟎
1.0966 0.0441 0.0014
=Δ5𝒚𝟎
1.8 6.0496 0.2429 0.0094
1.3395 0.0535
2.0 7.3891 0.2964
1.6359
2.2 9.0250
237
ℎ = 𝑥 − 𝑥 = 0.2
𝑥 = 1.2; 𝑦 = 𝟑. 𝟑𝟐𝟎𝟏
= [∆𝑦 − ∆ 𝑦 + ∆ 𝑦 − ∆ 𝑦 + ∆ 𝑦]
𝒅𝒚 .
(𝒅𝒙)𝟏.𝟏 = [0.7351 − 0.08135 + 0.012033 − 0.002 + 0.00028] = = 𝟑. 𝟑𝟐𝟎𝟑𝟏𝟓
. .
𝒅𝟐 𝒚 11 5
( ) = (0.1627) − 0.0361 + (0.0080) − (0.0014)
𝒅𝒙𝟐 𝟏.𝟐 ( . ) 12 6
𝒅𝟐 𝒚 .
(𝒅𝒙𝟐 ) = ( [ (0.1627) − 0.0361 + 0.00733 − 0.001166] = = 𝟑. 𝟑𝟏𝟗𝟏
. ) .
3. The following data gives the velocity of a particle for 20 seconds at an interval of 5 seconds. Find
the initial acceleration using the entire data
Time t (sec) 0 5 10 15 20
Velocity v (m/s) 0 3 14 69 228
Ans: Acceleration is a=dv/dt, first differential of velocity. The difference table is given by
Since it is mentioned that initial acceleration, we can take t=0 as 𝒙𝟎
t V Δ Δ2 Δ3 Δ4
0= 𝒙𝟎 0= 𝒚𝟎
3= Δ𝒚𝟎
5 3 8= Δ2𝒚𝟎
11 36=Δ3𝒚𝟎
10 14 44 24=Δ4𝒚𝟎
55 60
15 69 104
159
20 228
ℎ =𝑥 −𝑥 =5
𝑥 = 𝑡 = 0; 𝑦 = 0
= [∆𝑦 − ∆ 𝑦 + ∆ 𝑦 − ∆ 𝑦 + ∆ 𝑦]
238
( ) = [3 − (8) + (36) − (24)]
𝒅𝒚
(𝒅𝒙)𝒕 𝟎 = [3 − 4 + 12 − 6] = = 𝟏 m/s2
Ans: cos (1.74) is the first differential of sin (1.74). Take 𝑥 as 1.74. The forward difference table is
given by.
x sin x Δ Δ2 Δ3 Δ4
1.7 0.9916
-0.0059
1.74= 𝒙𝟎 0.9857= 𝒚𝟎 -0.0017
-0.0076= Δ𝒚𝟎 0.0003
1.78 0.9781 -0.0014= Δ2𝒚𝟎 -0.0006
-0.0090 -0.0003=Δ 𝒚𝟎 3
ℎ = 𝑥 − 𝑥 = 0.04
𝑥 = 1.74 = 0; 𝑦 = 0.9857
= [∆𝑦 − ∆ 𝑦 + ∆ 𝑦 − ∆ 𝑦 + ∆ 𝑦]
( ) . = .
[−0.0076 − (−0.0014) + (−0.0003)]
𝒅𝒚
(𝒅𝒙)𝒙 𝟏.𝟕𝟒 = [−0.0076 + 0.0007 − 0.0001] = −0.175
.
The process of evaluating a definite integral from a set of tabulated values of the integrand f(x) is called
numerical integration. The process when applied to a function of a single variable, is known as
quadrature.
239
• Trapezoidal rule
• Simpsons 1/3 rule
Let
𝐼= 𝑓(𝑥)𝑑𝑥 , 𝑦 = 𝑓(𝑥)
Let the interval [a,b] be divided into n equal sub-intervals such that a=x0 < x1 < x2 < ……….. < xn =b
𝑥 = 𝑥 + 𝑛ℎ
𝐼= 𝑦𝑑𝑥
( ) ( )( )
𝐼 = ∫ [𝑦 + 𝑝∆𝑦 + !
∆ 𝑦 + !
∆ 𝑦 + ⋯ ]𝑑𝑥 ………….(1)
240
𝑝 1 𝑝 𝑝 1 𝑝 3𝑝 2𝑝
𝐼 = ℎ[𝑦 𝑝 + ∆𝑦 + ( − ) ∆ 𝑦 + ( − + ) ∆ 𝑦 + ⋯]
2 2 3 2 6 4 3 2
𝑝 1 1
𝐼 = ℎ[𝑦 𝑝 + ∆𝑦 + 𝑝 (2𝑝 − 3)∆ 𝑦 + 𝑝 (𝑝 − 2) ∆ 𝑦 + ⋯ ]
2 12 24
𝒙 𝒏 𝟏 𝟏
𝑰 = ∫𝒙 𝒏 𝒚𝒅𝒙 = 𝒏𝒉[𝒚𝒐 + 𝟐 ∆𝒚𝒐 + 𝟏𝟐 𝒏(𝟐𝒏 − 𝟑)∆𝟐 𝒚𝒐 + 𝟐𝟒 𝒏(𝒏 − 𝟐)𝟐 ∆𝟑 𝒚𝒐 + ⋯ ] …………..(3)
𝟎
Set n=1 in equ (3) and taking the curve through (x0,y0) and (x1,y1) as a straight line when h is very small.
That is straight line is a polynomial of first order so that the differences of order higher than first become
zero, then equ (3) for the interval [x0, x1] become
1
𝑦𝑑𝑥 = ℎ(𝑦 + ∆𝑦 )
2
1
= ℎ[𝑦 + (𝑦 − 𝑦 )]
2
ℎ
= (𝑦 + 𝑦 )
2
For the next interval [x1, x2]
ℎ
𝑦𝑑𝑥 = (𝑦 + 𝑦 )
2
For the last interval [xn-1, xn]
ℎ
𝑦𝑑𝑥 = (𝑦 +𝑦 )
2
Combining all these expressions, we obtain
𝒙𝒏
𝒉
𝒚𝒅𝒙 = (𝒚 + 𝟐(𝒚𝟏 + 𝒚𝟐 + ⋯ + 𝒚𝒏 𝟏 ) + 𝒚𝒏 )
𝒙𝟎 𝟐 𝟎
Set n=2 in equ (3) and taking the curve through (x0,y0), (x1,y1) and (x2,y2) as a parabola, i.e. a polynomial
of second order so that differences of order higher than second vanish, for the interval (x0+2h) we get
241
1
𝐼= 𝑦𝑑𝑥 = 2ℎ 𝑦 + ∆𝑦 + ∆ 𝑦
6
= 2ℎ[𝑦 + (𝑦 − 𝑦 ) + (∆𝑦 − ∆𝑦 )]
= 2ℎ[𝑦 + (𝑦 − 𝑦 ) + (𝑦 − 𝑦 − 𝑦 + 𝑦 )]
=h 2[ ]
ℎ
𝑦𝑑𝑥 = [𝑦 + 4𝑦 + 𝑦 ]
3
Similarly
ℎ
𝑦𝑑𝑥 = [𝑦 + 4𝑦 + 𝑦 ]
3
In general
ℎ
𝑓(𝑥)𝑑𝑥 = [𝑦 + 4𝑦 +𝑦 ]
( ) 3
𝒙𝟎 𝒏
𝒉
𝒇(𝒙)𝒅𝒙 = [𝒚 + 𝟒(𝒚𝟏 + 𝒚𝟑 + ⋯ + 𝒚𝒏 𝟏) + 𝟐(𝒚𝟐 + 𝒚𝟒 + 𝒚𝟔 + ⋯ + 𝒚𝒏 𝟐) + 𝒚𝒏 ]
𝒙𝟎 𝟑 𝟎
1. From the following table, find the area bounded by the curve for x-axis from x=7.47 to x=7.52
x 7.47 7.48 7.49 7.50 7.51 7.52
y 1.93 1.95 1.98 2.01 2.03 2.06
Ans: 𝐼 = ∫ 𝑑𝑥; 𝑦 =
242
We can solve it for different values of h such as h=0.5, h=0.25,h=0.125
---------------------------------------------------------------------------------------------------------------------
h=0.5
x 0= 𝑥 0.5= 𝑥 1= 𝑥
y= 1=𝑦 0.6667= 𝑦 0.5= 𝑦
Trapezoidal rule
𝐼 = [𝑦 + 2(𝑦 ) + 𝑦 ]
.
= [1 + 2(0.6667) + 0.5]
= 0.25 × 2.8334
= 𝟎. 𝟕𝟎𝟖𝟑𝟓
Simpson’s rule
𝐼 = [𝑦 + 4(𝑦 ) + 𝑦 ]
.
= [1 + 4(0.6667) + 0.5]
= 0.1666 × 4.1668
= 𝟎. 𝟔𝟗𝟒𝟓
---------------------------------------------------------------------------------------------------------------------
h=0.25
x 0 0.25 0.5 0.75 1
y= 0.5714 0.5
1 0.8 0.6667
Trapezoidal rule
𝐼 = [𝑦 + 2(𝑦 + 𝑦 + 𝑦 ) + 𝑦 ]
.
= [1 + 2(0.8 + 0.6667 + 0.5714) + 0.5]
= 0.125 × 5.5762
= 𝟎. 𝟔𝟗𝟕𝟎
Simpson’s rule
𝐼 = [𝑦 + 4(𝑦 + 𝑦 ) + 2𝑦 + 𝑦 ]
.
= [1 + 4(0.8 + 0.5714) + 2(0.6667) + 0.5]
= 0.0833 × 8.319
= 𝟎. 𝟔𝟗𝟑𝟐
243
---------------------------------------------------------------------------------------------------------------------
h=0.125
x 0 0.125 0.25 0.375 0.5 0.625 0.75 0.875 1
y=
1 0.8889 0.8000 0.7273 0.6667 0.6154 0.5714 0.5333 0.5
𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦
Trapezoidal rule
𝐼 = [𝑦 + 2(𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 ) + 𝑦 ]
.
= [1 + 2(00.8889 + 0.8000 + 0.7273 + 0.6667 + 0.6154 + 0.5714 + 0.5333) + 0.5]
= 0.0625 × 11.1.06
= 𝟎. 𝟔𝟗𝟒𝟏𝟐𝟓
Simpson’s rule
𝐼 = [𝑦 + 4(𝑦 + 𝑦 + +𝑦 + +𝑦 ) + 2(𝑦 + 𝑦 + 𝑦 ) + 𝑦 ]
.
= [1 + 4(0.8889 + 0.7273 + 0.6154 + 0.5333) + 2(0.8000 + 0.6667 + 0.5714) + 0.5]
= 0.04166 × 16.6358
= 𝟎. 𝟔𝟗𝟑𝟎
Ans:
𝑦=𝑒
For 10 intervals take h=0.2
x 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6
x2 0 0.04 0.16 0.36 0.64 1 1.44 1.69 2.56
y=𝑒 1 1.0408 1.1735 1.4333 1.8964 2.1782 4.2206 7.0993 12.9358
𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦
1.8 2
3.24 4
25.5337 54.5981
𝑦 𝑦
𝐼 = [𝑦 + 2(𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 + 𝑦 ) + 𝑦 ]
.
= [1 + 2(1.0408 + 1.1735 + 1.4333 + 1.8964 + 2.1782 + 4.2206 + 7.0993) + 54.5981 +
12.9358 + 25.5337]
= 0.1[1 + 115.0232 + 54.598]
244
= 0.1[170.6212]
=17.062
.
4. Use simpson’s 1/3rd rule to find ∫ 𝑒 𝑑𝑥 by taking seven ordinals
Ans: 𝑦 = 𝑒
x 0 0.1 0.2 0.3 0.4 0.5 0.6
x2 0 0.01 0.04 0.09 0.10 0.25 0.36
y=𝑒 1 0.9900 0.9608 0.9139 0.8521 0.7788 0.6977
𝑦 𝑦 𝑦 𝑦 𝑦 𝑦 𝑦
h=0.1
By using simpon’s 1/3rd rule
.
𝐼=∫ 𝑒 𝑑𝑥 = [𝑦 + 4(𝑦 + 𝑦 + 𝑦 ) + 2(𝑦 + 𝑦 ) + 𝑦 ]
. .
𝐼=∫ 𝑒 𝑑𝑥 = [1 + 4(0.9900 + 0.9139 + 0.7788 ) + 2(0.9608 + 0.8521) + 0.6977]
.
= [1 + 4(2.6827) + 2(1.8129) + 0.6977]
= 0.0333[16.0543]
=0.5351
program
245
Algorithm
Example
Script file
Program_132.py
1 from numpy import*
2 from math import* 1
𝑑𝑥
3 def f(x): 1+𝑥
4 return (1/(1+x))
5 a=float(input('Enter the lower limit of a=0
integration:'))
6 b=float(input('Enter the upper limit of b=1
integration:'))
7 n=int(input('Enter the number of sub intervals n=2
required:'))
8 h=(b-a)/n 1−0
9 print(h) ℎ= = 0.5
2
10 integral=f(a)+f(b) integral=1+0.5
11 for i in range (1,n): i=[1]
12 x=a+i*h x=0+1*0.5
13 integral=integral+2*f(x) integral=1+0.5+y1
14 integral=(h/2)*integral integral=(h/3)integral
15 print('Integral,I=',integral)
Output
IDLE Shell 3.10.4
>>> Enter the lower limit of integration:0
Enter the upper limit of integration:1
Enter the number of sub intervals required:2
0.5
Integral,I= 0.7083333333333333
>>> Enter the lower limit of integration:0
Enter the upper limit of integration:1
Enter the number of sub intervals required:4
0.25
Integral,I= 0.6970238095238095
>>> Enter the lower limit of integration:0
Enter the upper limit of integration:1
Enter the number of sub intervals required:8
0.125
Integral,I= 0.6941218503718504
3. Use the Trapezoidal rule to estimate the integral ∫ 𝑒 𝑑𝑥 taking 10 intervals [Ans: 17.062]
4. Write and execute a python program to evaluate the ∫ sin 𝑥 𝑑𝑥 using Trapezoidal rule of
integration.
246
---------------------------------------------------------------------------------------------------------------------------
Python program: Simpson’s 1/3rd Rule
𝒙𝟎 𝒏𝒉
𝒉
𝒇(𝒙)𝒅𝒙 = [𝒚 + 𝟒(𝒚𝟏 + 𝒚𝟑 + ⋯ + 𝒚𝒏 𝟏) + 𝟐(𝒚𝟐 + 𝒚𝟒 + 𝒚𝟔 + ⋯ + 𝒚𝒏 𝟐) + 𝒚𝒏 ]
𝒙𝟎 𝟑 𝟎
𝒉
= [𝒚 + 𝒚𝒏 + 𝟒(𝒐𝒅𝒅 𝒗𝒂𝒍𝒖𝒆𝒔 𝒐𝒇 𝒚) + 𝟐(𝒆𝒗𝒆𝒏 𝒗𝒂𝒍𝒖𝒆𝒔 𝒐𝒇 𝒚)]
𝟑 𝟎
Algorithm
247
15 integral=integral+4*f(x) integral=integral+4(y1+y3)
16 integral=(h/3)*integral integral=(h/3)[integral+2(y2)
17 print('The value of the given +4(y1+y3)
integral=',integral)
Output
IDLE Shell 3.10.4
>>> Enter the lower limit of integration:0
Enter the upper limit of integration:1
Enter the number of sub intervals required:2
h= 0.5
The value of the given integral= 0.6944444444444443
>>> Enter the lower limit of integration:0
Enter the upper limit of integration:1
Enter the number of sub intervals required:4
h= 0.25
The value of the given integral= 0.6932539682539682
>>> Enter the lower limit of integration:0
Enter the upper limit of integration:1
Enter the number of sub intervals required:8
h= 0.125
The value of the given integral= 0.6931545306545306
The solution of an ordinary differential equation means finding an explicit expression for y in terms of
a finite number of elementary functions. Such a solution of differential equation is known as closed or
finite form of solution. In the absence of such a solution, we use numerical methods to find the solution.
Suppose the solution of equ (1) is a curve as shown below, where the curve is approximated using a
tangent at the point P at (x0,y0)
248
Let us assume LM is divided into n sub-intervals each of width h. At P1, y1 can be written as
𝑦 = 𝑦 + 𝑃𝑅 tan 𝜃
𝑑𝑦
𝑦 = 𝑦 + ℎ( )
𝑑𝑥
similarly
𝑦 = 𝑦 + ℎ 𝑓(𝑥 + ℎ, 𝑦 )
𝑦 = 𝑦 + ℎ 𝑓(𝑥 + 2ℎ, 𝑦 )
In general
This is the Euler method of finding the approximate solution of equ (1)
In the above figure, y1 at (x0+h) is better approximated by taking the slop of the curve as the mean of
the slope of the tangents at P and P1. That is
ℎ
𝑦 =𝑦 + [𝑓(𝑥 , 𝑦 ) + 𝑓(𝑥 + ℎ, 𝑦 )]
2
1
𝑦 =𝑦 + [ℎ𝑓(𝑥 , 𝑦 ) + ℎ𝑓(𝑥 + ℎ, 𝑦 )]
2
𝟏
𝒚𝟏 = 𝒚𝟎 + [𝒌 + 𝒌𝟐 ]
𝟐 𝟏
249
Where 𝑘 = ℎ𝑓(𝑥 , 𝑦 ) and 𝑘 = ℎ𝑓(𝑥 + ℎ, 𝑦 ) = ℎ𝑓(𝑥 + ℎ, 𝑦 + 𝑘 )
Similarly
ℎ
𝑦 =𝑦 + [𝑓(𝑥 + ℎ, 𝑦 ) + 𝑓(𝑥 + 2ℎ, 𝑦 )]
2
And so on
1. Given = with initial condition y=1 at x=0. Find y for x=0.1 by Euler’s method
Ans: Given =
That is 𝑓(𝑥, 𝑦) =
At x=0, y=1
𝒚 𝒙
x y 𝒇(𝒙, 𝒚) = 𝒚 New y; 𝒚𝒏 = 𝒚𝒏 𝟏 + 𝒉𝒇(𝒙, 𝒚)
𝒙
𝒙𝟓 0.1 1.0928
2. Using Euler’s method, find an approximate value of y corresponding to x=1, given that =𝑥+𝑦
250
Therefore 𝑓(𝑥, 𝑦) = 𝑥 + 𝑦
1. Using Modified Euler’s method, find an approximate value of y when x=0.3, given that =𝑥+
Ans: = 𝑥 + 𝑦 = 𝑓(𝑥, 𝑦)
𝑤ℎ𝑒𝑛 𝑥 = 0; 𝑦 = 1
𝑓(𝑥 , 𝑦 ) + 𝑓(𝑥 + ℎ, 𝑦 )
𝑚𝑒𝑎𝑛 𝑠𝑙𝑜𝑝𝑒 =
2
251
0.1 1.1 0.1+1.1=1.2 1 + 1.2 𝑦 = 1 + 0.1 × 1.1 = 1.11
= 1.1
2
0.1 1.11 0.1+1.11=1.21 1 + 1.21 𝑦 = 1 + 0.1 × 1.105 = 1.1105
2
= 1.105
Comment: in the previous step, mean solpe is taken between x=0 and x=0.1. Similarly in the last
column, old y is the value of y at x=0
0.1 1.1105 0.1+1.1105 1 + 1.2105 𝑦 = 1 + 0.1 × 1.1052 = 1.1105
=1.2105 2
= 1.1052
Since the last two y values are same, we take 𝑦(0.1) = 1.1105
252
Since the last two y values are same, we take 𝑦(0.3) = 1.4004
Ans: = log(𝑥 + 𝑦)
𝑤ℎ𝑒𝑛 𝑥 = 0; 𝑦 = 2
Since the last two y values are same, we take 𝑦(0.3) = 1.4004
253
3.9 Taylor series expansion of sin(x) and cos (x)
If a function and its derivatives are known at some point x=a, we can express f(x) in the vicinity of
that point using a polynomial. The Taylor series expansion is given by
(𝑥 − 𝑎) (𝑥 − 𝑎)
𝑓(𝑥) = 𝑓(𝑎) + (𝑥 − 𝑎)𝑓 (𝑎) + 𝑓 (𝑎) + − − − + 𝑓 (𝑎)
2! 𝑛!
For deriving the Taylor series of sin(x), put f(x)=sin (x) and a=0, then the series is known as
Maclaurin series. So the series become,
( ) ( ) ( ) ( )
𝑓(𝑥) = 𝑓(0) + (𝑥)𝑓 (0) + !
𝑓 (0) + !
𝑓 (0) + !
𝑓 (0) − − − +
!
𝑓 (0) …….(1)
𝑥 𝑥 𝑥
𝑓(𝑥) = sin 𝑥 = 𝑥 − + − +−−−
3! 5! 7!
Program:
254
𝑥 𝑥 𝑥
𝑓(𝑥) = sin 𝑥 = 𝑥 − + − +−−−
3! 5! 7!
=( )!
, for n=0….n
=( )!
, for m=0….m
Algorithm
Script file
Program_132.py
1 from math import*
2 a=float(input('Enter an angle in degree='))
3 x=radians(a)
4 s=0
5 n=0
6 while True:
7 t=x**(2*n+1)/factorial(2*n+1)
8 s=s+(-1)**n*t
9 if t<0.000001:
10 break
11 n=n+1
12 print('sin',a,'=',s)
13
14 c=0
15 m=0
16 while True:
17 t=x**(2*m)/factorial(2*m)
18 c=c+(-1)**m*t
19 if t<0.000001:
20 break
21 m=m+1
22 print('cos',a,'=',c)
Output
IDLE Shell 3.10.4
>>> Enter an angle in degree=90
sin 90.0 = 1.0000000006627803
cos 90.0 = 6.321469515740575e-09
>>> Enter an angle in degree=45
sin 45.0 = 0.7071067829368671
cos 45.0 = 0.7071067810719247
>>> Enter an angle in degree=30
sin 30.0 = 0.5000000000202799
cos 30.0 = 0.8660254042103523
255
>>> Enter an angle in degree=60
sin 60.0 = 0.8660254034934827
cos 60.0 = 0.4999999963909432
>>> Enter an angle in degree=0
sin 0.0 = 0.0
cos 0.0 = 1.0
Chapter-4
Computational Methods in Physics and Computer
Simulations
256
257
Contents Page
1 Classical Mechanics: 1D simulations
• Freely falling body (Euler Method)
• Fall of a body in viscous medium (Euler Method)
2 Classical Mechanics: 2D simulations
• Projectile motion (Euler Method)
3 Monte Carlo simulations
• Simulation of radio activity
258
4.2 Importance of Python simulation in Physics
Python simulation in physics holds immense importance for several reasons, contributing significantly
to research, education, and practical applications. Here are key aspects highlighting the importance of
Python simulation in physics:
Numerical Simulations: Python's numerical computing libraries, such as NumPy and SciPy, facilitate
the implementation of numerical simulations. Physicists can model and simulate complex physical
systems, solving differential equations and performing numerical analyses to understand the behavior
of systems over time.
Complex System Modeling: Physics often deals with complex systems that may not have analytical
solutions. Python allows physicists to model and simulate such systems, including chaotic and nonlinear
systems, providing insights into their behavior that may be challenging to derive analytically.
Quantum Mechanics Simulations: Python is widely used for simulating quantum systems. Libraries
like QuTiP (Quantum Toolbox in Python) enable physicists to model and analyze quantum circuits,
simulate quantum algorithms, and explore quantum entanglement, contributing to the field of quantum
mechanics research.
Statistical Mechanics and Thermodynamics: Python is suitable for simulating statistical mechanics
and thermodynamics systems. Monte Carlo simulations, molecular dynamics simulations, and other
statistical approaches can be implemented using Python, aiding in the study of phase transitions,
thermodynamic properties, and statistical behavior of particles.
Fluid Dynamics and Computational Physics: Python is employed in simulating fluid dynamics and
solving partial differential equations relevant to computational physics. Libraries like PyTorch and
259
TensorFlow are used for implementing machine learning models that can be applied to fluid flow
simulations, enhancing understanding and prediction capabilities.
Astrophysics and Cosmology Simulations: Python is widely used in astrophysics and cosmology for
simulating astronomical phenomena. Researchers use Python to model galaxy formations, simulate
celestial events, and analyze large astronomical datasets. The flexibility and scalability of Python make
it well-suited for handling these complex simulations.
Integration with Experimental Data: Python simulations can be integrated with experimental data,
allowing physicists to compare theoretical models with real-world observations. This integration
supports the validation of theoretical predictions, refinement of models, and a better understanding of
the relationship between theory and experiment.
Educational Tool: Python simulations are valuable educational tools in physics courses. Students can
gain hands-on experience by implementing simulations, visualizing physical phenomena, and
experimenting with different parameters. This enhances the learning experience and helps students
develop computational skills.
Open Source and Collaboration: Python's open-source nature encourages collaboration and sharing
of simulation code within the scientific community. Physicists can build upon existing work, reproduce
simulations, and contribute to the collective knowledge in physics.
Parallel and High-Performance Computing: Python can be used in conjunction with tools like Dask,
mpi4py, and other parallel computing libraries for high-performance computing. This allows physicists
to scale simulations, handle large datasets, and perform computationally intensive tasks efficiently.
In summary, Python simulation in physics is essential for its versatility, ease of use, and the wide array
of libraries available. It empowers physicists to model, simulate, and analyze diverse physical
phenomena, contributing to advancements in our understanding of the natural world. The accessibility
of Python also makes it a valuable tool for researchers, students, and educators in the field of physics.
Accuracy: Computational techniques can provide highly accurate results, especially when dealing with
complex physical phenomena that are difficult to solve analytically.
Efficiency: Computers can perform numerous calculations quickly, enabling researchers to explore a
wide range of scenarios and parameter variations efficiently.
Visualization: Computational techniques often include tools for visualizing results, which can aid in
understanding the behavior of physical systems and interpreting the data.
260
Flexibility: Computational models can be easily modified and adapted to study different aspects of a
problem or incorporate new findings.
Accessibility: With the availability of powerful computational resources and software packages, these
techniques are becoming increasingly accessible to researchers and engineers.
Disadvantages:
Sensitivity to Assumptions: Computational models rely on assumptions and simplifications, which may
not always accurately represent the real-world complexity of physical systems.
Resource Intensive: Solving complex physical problems computationally can require significant
computational resources, including high-performance computing clusters or specialized hardware.
Validation and Verification Challenges: It can be challenging to validate and verify the accuracy of
computational models, particularly when experimental data is limited or unavailable.
Interpretation Complexity: Analyzing the results of computational simulations can be complex,
requiring expertise in both the underlying physics and computational techniques.
Potential for Errors: Errors in coding, numerical methods, or input data can lead to inaccurate results,
requiring careful debugging and validation procedures.
• When the object is under free Fall, the initial velocity (u) is always zero, since there is no force
acting on the object just when it is dropped. Therefore, u = 0.
• Under free fall, no other force than the acceleration due to gravity acts upon the object, which
means, even air friction or air resistance is also assumed to be zero.
• The objects start to experience a constant acceleration which is equal to the acceleration due to
gravity (g= 9.8 m/sec2).
• Once the object is dropped from a certain height, its velocity keep on increasing a constant rate
and body covers longer distance in successive interval of time
𝑠 = 𝑈𝑡 + 𝑎𝑡 ………………………………...(1)
𝑉 = 𝑈 + 𝑎𝑡 ………………………………...(2)
𝑉 = 𝑈 + 2𝑎𝑠 ………………………………...(3)
For a freely falling body from a height H (or y, vertical distance), the initial velocity U=0 and the
acceleration due to gravity is g. Therefore the above equations reduce to
𝐻 = 𝑔𝑡 ………………………………...(4)
261
𝑉 = 𝑔𝑡 ………………………………...(5)
𝑉 = 2𝑔𝐻 ………………………………...(6)
But for simulating the free fall, an approach based on Euler method is adopted
Since the body is falling vertically, the velocity and position coordinate have only y-component.
Therefor the velocity component can be written as
𝑣 = 𝑣 + ℎ 𝑓1(𝑡, 𝑦, 𝑣)
Here f1(t,y,v) denote the vertical acceleration given by g=-9.8 m/s2 and h denotes the increment in time,
t. Similarly, the position coordinate is given by
𝑦 = 𝑦 + ℎ 𝑓2(𝑡, 𝑦, 𝑣)
where f2(t,y,v) corresponds to vertical velocity, v.
Euler method
Consider the differential equation dy/dx=f(x,y), where y(x0)=y0, where x0 and y0 are the initial
conditions of the given problem. Suppose we want to find successively y1,y2,y3……,yn where yn is the
value of y corresponding to x=xn, where xn=x0+nh, n=1,2,…..and h being a small quantity. Here we use
the property that in small interval, a curve is nearly a straight line as shown in figure
Thus in the interval, x0 to x1 of x, we can approximate the curve by the tangent at the point (x0,y0)
Therefore the equation of the tangent at (x0,y0) is
262
𝑦−𝑦 𝑑𝑦
=
𝑥−𝑥 𝑑𝑥 ( , )
Or
𝑦−𝑦
= 𝑓(𝑥 , 𝑦 )
𝑥−𝑥
𝑦 − 𝑦 = 𝑓(𝑥 , 𝑦 )(𝑥 − 𝑥 )
𝑦 = 𝑦 + 𝑓(𝑥 , 𝑦 )(𝑥 − 𝑥 )
Hence the value of y corresponding to x=x1 is
𝑦 = 𝑦 + (𝑥 − 𝑥 ) 𝑓(𝑥 , 𝑦 )
𝑦 = 𝑦 + ℎ 𝑓(𝑥 , 𝑦 )
Similarly approximating the curve in the next interval [x 1,x2] by a line through (x1,y1) with slope of
f(x,y1), we get
𝑦 = 𝑦 + ℎ 𝑓(𝑥 , 𝑦 )
In general it can be shown that
𝑦 = 𝑦 + ℎ 𝑓(𝑥 , 𝑦 )
In general, while programming, the position or the y component can be written as
𝑦 = 𝑦 + ℎ 𝑓2(𝑡, 𝑦, 𝑣)
Similarly, the velocity coordinate can be written as
𝑣 = 𝑣 + ℎ 𝑓1(𝑡, 𝑦, 𝑣)
(same as v=u+at, h=t and f1=g=a)
Script file
Program_132.py
1 import pylab as pl
2
3 t=0
4 v=0
5 a=9.8
6
7 y=float(input('Enter the height at which the body is dropped,y='))
8 h=float(input('Enter the time step,h='))
9 Te=pl.sqrt(2*y/9.8) #Theorectical value of time to reach the ground
10 ve=pl.sqrt(2*9.8*y) #Theoretical value of final velocity
11 print('Te=',Te)
12 print('ve=',ve)
13
14 ydata=[y]
15 tdata=[t]
16 vdata=[v]
17 print(' t ',' y ',' v')
18
19 while(y>=0):
20 v=v+h*a
21 y=y-h*v
22 t=t+h
23 ydata.append(y)
24 vdata.append(v)
25 tdata.append(t)
263
26 print('%2.4f %7.4f %7.4f'%(t,y,v))
27
28 Tsim=max(tdata)
29 vsim=max(vdata)
30 print('Tsim=',Tsim)
31 print('vsim=',vsim)
32
33 pl.subplot(1,3,1)
34 pl.plot(tdata,ydata,'*r')
35 pl.title('Free fall')
36 pl.xlabel('time(sec)')
37 pl.ylabel('Height(m)')
38 pl.grid()
39
40 pl.subplot(1,3,2)
41 pl.plot(tdata,vdata,'*b')
42 pl.title('Free fall')
43 pl.xlabel('time(sec)')
44 pl.ylabel('velocity(m/s)')
45 pl.grid()
46
47 adata=pl.diff(vdata)/h
48 pl.subplot(1,3,3)
49 pl.plot(tdata[0:len(adata)],adata,'g*')
50 pl.xlabel('time(s)')
51 pl.ylabel('accelaration, a (m/s^2)')
52 pl.title('accelaration-time graph')
53 pl.ylim([-1,10])
54 pl.grid()
55 pl.show()
Output
IDLE Shell 3.10.4
>>> Enter height at which body is dropped,y:100
Time step,h:0.01
Time= 4.5175395145262565 (sec)
final velocity= 44.271887242357316 (m/s)
t y v
0.0100 99.9990 0.0980 9.8000
0.0200 99.9971 0.1960 9.8000
0.0300 99.9941 0.2940 9.8000
0.0400 99.9902 0.3920 9.8000
0.0500 99.9853 0.4900 9.8000
0.0600 99.9794 0.5880 9.8000
0.0700 99.9726 0.6860 9.8000
0.0800 99.9647 0.7840 9.8000
0.0900 99.9559 0.8820 9.8000
------------------------------
------------------------------
4.4300 3.6209 43.4140 9.8000
264
4.4400 3.1858 43.5120 9.8000
4.4500 2.7497 43.6100 9.8000
4.4600 2.3126 43.7080 9.8000
4.4700 1.8746 43.8060 9.8000
4.4800 1.4355 43.9040 9.8000
4.4900 0.9955 44.0020 9.8000
4.5000 0.5545 44.1000 9.8000
4.5100 0.1125 44.1980 9.8000
4.5200 -0.3304 44.2960 9.8000
Tsim= 4.519999999999948
vsim= 44.29599999999976
Output
The accuracy of the simulation depends on the value of h(time step). With decreaing h, the accuracy
will increase.
As it can be seen from the second figure, the slope of the plot is a constant which is equal to 9.8,
accelaration due to gravity.
4.4.2 Motion of a body dropped into a heavily viscous medium (Euler’s method)
When a small object moves in a viscous medium it experiences a resistive force that is opposite in
direction to its velocity and directly proportional to its speed. For this problem, assume that the object
only moves up and down and take the upward direction to be positive. We write the viscous drag force
as Fv = -bv, where b is a constant. Same as in the case of free fall, the initial velocity is zero. As soon
as the body is released, the velocity of the body begins to increase because of the acceleration due to
gravity. Simultaneously the effect of viscosity is to oppose the downward motion of the body which
results in decreasing the velocity. Finally due to the combined effect of both the forces, the body will
move downward with a constant velocity until it takes rest at the bottom of the medium.
265
Consider the object as a spherical body falling in a viscous medium.
Denote as f2(t,y,v) and as f1(t,y,v)=-9.8-cv, where c=b/m is the coefficient of viscous drag, b is
a constant of proportionality that depends on the shape of the mass and medium through which it moves
and v is the instantaneous velocity
According to the Euler method position can be written as
𝑦 = 𝑦 + ℎ𝑓2(𝑡, 𝑦, 𝑣)
According to the Euler method 𝑣𝑒𝑙𝑜𝑐𝑖𝑡𝑦 can be written as
𝑣 = 𝑣 + ℎ𝑓1(𝑡, 𝑦, 𝑣)
(Same as v=u+a*t where a= 𝑓2(𝑡, 𝑦, 𝑣) and t =h)
Script file
Program_132.py
1 import pylab as pl
2
3 t=0
4 v=0
5 a=9.8
6
7 y=float(input('Enter the height at which the body is dropped,y='))
8 c=float(input('Enter the value of coefficient of viscosity:'))
9 h=float(input('Enter the time step,h='))
10
11 ydata=[y]
12 tdata=[t]
266
13 vdata=[v]
14 print(' t ',' y ',' v')
15
16 while(y>=0):
17 v=v+h*(a-c*v)
18 y=y-h*v
19 t=t+h
20 ydata.append(y)
21 vdata.append(v)
22 tdata.append(t)
23 print('%2.4f %7.4f %7.4f'%(t,y,v))
24
25 Tsim=max(tdata)
26 vsim=max(vdata)
27 print('Tsim=',Tsim)
28 print('vsim=',vsim)
29
30 pl.subplot(1,2,1)
31 pl.plot(tdata,ydata,'*r')
32 pl.title('Free fall')
33 pl.xlabel('time(sec)')
34 pl.ylabel('Height(m)')
35 pl.grid()
36
37 pl.subplot(1,2,2)
37 pl.plot(tdata,vdata,'*b')
39 pl.title('Free fall')
40 pl.xlabel('time(sec)')
41 pl.ylabel('velocity(m/s)')
42 pl.grid()
43
44 pl.show()
Output
IDLE Shell 3.10.4
>>> Enter the coefficient of viscosity,c:1
Enter height at which body is dropped,y:10
Time step,h:0.01
Output
267
4.5 Classical Mechanics: 2D simulation
4.5.1 Projectile motion (Using Euler’s method)
Projectile motion is a form of motion experienced by a body (or projectile) that is thrown near the
Earth’s surface and moves along a curved path under the action of gravity only (neglecting the effect of
air resistance)
The common questions of interest are
1. How high will it go up (Height, H)?
2. What is the maximum horizontal distance it travelled (Range, R)?
3. What is the time of flight (T) ?
Theory
Consider a body is projected at some angle ‘ ’ (angle of projection) with an initial velocity ‘U’ as shown
in figure. Let us fix the cartesian co-ordinates with origin coinciding with the point where the body has
projected and take X and Y axis along the horizontal and vertical directions respectively.
268
Initial conditions (U and θ)
The outcome of a projectile such as maximum height, the distance travelled by the body horizontally
(range) and time of flight depend only on initial conditions U and θ, where, 𝑈 𝑖𝑠 𝑡ℎ𝑒 𝑖𝑛𝑖𝑡𝑖𝑎𝑙 𝑣𝑒𝑙𝑜𝑐𝑖𝑡𝑦
and 𝜃 𝑖𝑠 𝑡ℎ𝑒 𝑎𝑛𝑔𝑙𝑒 𝑜𝑓 𝑝𝑟𝑜𝑗𝑒𝑐𝑡𝑖𝑜𝑛
Here U has both x and y-components.
𝑈 = 𝑈 cos 𝜃 is the x-component of initial velocity U
𝑈 = 𝑈 sin 𝜃 is the y-component of initial velocity U
Similarly, acceleration a also has x and y components given by
𝑎 = 0, horizontal component of acceleration is zero
𝑎 = −9.8, vertical component of acceleration(+y direction) is -9.8 since the direction of acceleration
due to gravity is pointing downward
Outcome of projectile
Our point of interest in a projectile motion are the following
1. Range (R)
2. Height (H)
3. Time of flight (T)
Underlying Physics
Underlying physics rely on newtons equation of motion.
1. 𝑆 = 𝑈𝑡 + 𝑎𝑡
2. 𝑉 = 𝑈 + 𝑎𝑡
3. 𝑉 = 𝑈 + 2𝑎𝑠
Where S is the distance travelled by the object (x or y), V is the final velocity or velocity at any instant
of time and a is the acceleration.
Derivation of R, H and T
Position co-ordinates (x,y) of the object are calculates as follows
269
We have three equations from Newtons equation of motion
𝑆 = 𝑈𝑡 + 𝑎𝑡 ………………………………...(1)
𝑉 = 𝑈 + 𝑎𝑡 ………………………………...(2)
𝑉 = 𝑈 + 2𝑎𝑆 ………………………………...(3)
Where s is the displacement, U is the initial velocity, V is the final velocity, a is the acceleration due to
gravity and t is the time of motion
From equ (1), x-coordinate of the motion can be written as
1
𝑥 =𝑈 𝑡+ 𝑎 𝑡
2
Substituting Ux and ax values
𝑥 = 𝑈𝑐𝑜𝑠 (𝜃) 𝑡 + 0
𝑥 = 𝑈𝑡 𝑐𝑜𝑠 (𝜃) ………………………………...(4)
𝑡= ( )
……………………………..(5)
y-coordinate become
1
𝑦=𝑈 𝑡+ 𝑎 𝑡
2
Substituting Uy and ay values
𝑦 = 𝑈𝑡 sin(𝜃) − 𝑔𝑡 …………………..…………(6)
ay=-g, since projectile motion is upward while comparing with the downward acceleration
Trajectory of the projectile ‘y’
substitute t from equ (5) in equ (6)
𝑈𝑥 sin(𝜃) 1 𝑥
𝑦= − 𝑔( )
𝑈 cos(𝜃) 2 𝑈𝑐𝑜𝑠 (𝜃)
𝒈𝒙𝟐
𝒚 = 𝒙 𝐭𝐚𝐧(𝜽) − 𝟐𝑼𝟐 𝐜𝐨𝐬 𝟐 𝜽…………………………(7)
𝒚 = 𝒙 𝐭𝐚𝐧(𝜽) − 𝒌𝒙𝟐………………………………(8)
Where 𝑘 = ( )
This is an equation of parabola (y=ax2+k form). That is the trajectory of the projectile is a parabola,
i.e, the plot of ‘x’ and ‘y’ co-ordinate is a parabola.
Horizontal distance, Range ‘R’
Th horizontal distance or range ‘x’ or normally denoted suing ‘R’ covered by the projectile can be
obtained by putting y=0 in equ (7)
𝑔𝑥
𝑥 tan(𝜃) =
2𝑈 cos 𝜃
2𝑈 cos (𝜃) tan(𝜃) 2𝑈 cos 𝜃 sin(𝜃) 𝑈 2sin(𝜃) cos(𝜃)
𝑥= = = =
𝑔 𝑔 cos(𝜃) 𝑔
270
𝑼𝟐 𝐬𝐢𝐧(𝟐𝜽)
𝑹=
𝒈
Maximum height attained by the projectile, H
The expression for maximum height attained by the projectile is obtained from equ (3). At maximum
height final velocity V =0 and U can be denoted using vertical component Uy and displacement s can
be replaced by height H
0 = 𝑈 𝑠𝑖𝑛 (𝜃) + 2(−𝑔)𝐻
𝑼𝟐 𝒔𝒊𝒏𝟐(𝜽)
𝑯=
𝟐𝒈
Time of flight, T
In equ (6) substitute y=0, final displacement in the y-direction
𝑈𝑡 sin(𝜃) = 𝑔𝑡
1
𝑈 sin(𝜃) = 𝑔𝑡
2
𝟐𝑼 𝐬𝐢𝐧(𝜽)
𝑻=
𝒈
Similarly,
𝑦 =𝑦 + ℎ𝑣 -------------------------- (2)
271
Also
𝑣𝑥 = 𝑣𝑥 + ℎ𝑎 -------------------------- (3)
Where 𝑣𝑥 is the x-component of velocity and 𝑎𝑥 is the x-component of acceleration.
Similarly,
𝑣𝑦 = 𝑣𝑦 + ℎ𝑎 -------------------------- (4)
From equ (1), (2), (3) and (4), it can be understood that to find x and y, we need vx and vy. To find vx
and vy, we need ax and ay, where the values of ax and ay is already known as 𝑎 = 0 and 𝑎 = −9.8.
Euler’s method
The components x, y, vx and vy are estimated using Euler’s method. The general formula of Euler’s
method is
𝑦 =𝑦 + ℎ ∗ 𝑓(𝑥 ,𝑦 )
Or
𝑦 =𝑦 + ℎ ∗ slop
This equation can be used to estimate x, y, vx and vy at different instant of time t as follows
𝑣𝑥 = 𝑣𝑥 + ℎ ∗ = 𝑣𝑥 + ℎ ∗ 𝑎𝑥 = 𝑣𝑥 + ℎ ∗ 𝑓1(𝑡, 𝑥, 𝑣𝑥)
𝑣𝑦 = 𝑣𝑦 + ℎ ∗ = 𝑣𝑦 + ℎ ∗ 𝑣𝑦 = 𝑣𝑦 + ℎ ∗ 𝑓2(𝑡, 𝑥, 𝑣𝑥)
1.Write a program to estimate the time of flight, range and height of a projectile motion
272
Script file
Program_132.py
1 from pylab import*
2 g=-9.8
3 theta=float(input('Enter projection angle, theta='))
4 U=float(input('Enter velocity,U='))
5 rtheta=theta/57.3
6 g=9.8
7 T=2*U*sin(rtheta)/g
8 H=U**2*sin(rtheta)**2/(2*g)
9 R=U**2*sin(2*rtheta)/g
10 print('T=',T)
11 print('H=',H)
12 print('R=',R)
Output
IDLE Shell 3.10.4
>>> Enter projection angle, theta=45
>>> Enter velocity,U=45
T= 6.493462111822251
H= 51.652186492147095
R= 206.6326516782168
273
21 tdata=[] #null list to store simulated t values
22
23 print(' t ',' x ',' y ',' vx ',' vy ')
24 while y>=0: #run loop till y=0, means the object touch the ground at y=0
25 vx=vx+h*ax #x-component of velocity using Euler's method
26 vy=vy+h*ay #y-component of velocity using Euler's method
27 x=x+h*vx #Genereated x coordinate
28 y=y+h*vy #Generated y coordinate
29 t=t+h #increment time
30 xdata.append(x) #store x value in null list named xdata
31 ydata.append(y) #store y value in null list named ydata
32 tdata.append(t)
33 print('%2.4f %7.4f %7.4f %7.4f %7.4f'%(t,x,y,vx,vy)) #formatted print
34 statement
35 g=9.8 # acceleration due to gravity
36 R=u**2*pl.sin(2*rtheta)/g # Theoretical value of Range, R
37 H=u**2*pl.sin(rtheta)**2/(2*g) # Theoretical value of Height, H
38 T=2*u*pl.sin(rtheta)/g # Theoretical value of time of flight, T
39 print('R=',R)
40 print('H=',H)
41 print('T=',T)
42
43 Rsim=max(xdata) # Simulated value of Range,R
44 Hsim=max(ydata) # Simulated value of Height, H
45 Tsim=max(tdata) # Simulated value of Time of flight, T
46 print('Rsim=',Rsim)
47 print('Hsim=',Hsim)
48 print('Tsim=',Tsim)
49
50 pl.plot(xdata,ydata,'r*')
51 pl.xlabel('Horizontal distance,x')
52 pl.ylabel('Vertical distance,y')
53 pl.title('Projectile motion')
54 pl.grid()
55 pl.show()
Output
IDLE Shell 3.10.4
>> Enter the value of initial velocity, u(m/s):45
Enter the value of angle of proejection:45
Enter time step:0.01
Output
t x y ux uy
0.0100 0.3182 0.3172 31.8216 31.7200
0.0200 0.6364 0.6334 31.8216 31.6220
0.0300 0.9546 0.9487 31.8216 31.5240
0.0400 1.2729 1.2629 31.8216 31.4260
0.0500 1.5911 1.5762 31.8216 31.3280
0.0600 1.9093 1.8885 31.8216 31.2300
274
0.0700 2.2275 2.1998 31.8216 31.1320
0.0800 2.5457 2.5102 31.8216 31.0340
0.0900 2.8639 2.8195 31.8216 30.9360
---------------------------------------------------------
---------------------------------------------------------
6.4100 203.9767 2.3074 31.8216 -31.0000
6.4200 204.2950 1.9964 31.8216 -31.0980
6.4300 204.6132 1.6844 31.8216 -31.1960
6.4400 204.9314 1.3715 31.8216 -31.2940
6.4500 205.2496 1.0576 31.8216 -31.3920
6.4600 205.5678 0.7427 31.8216 -31.4900
6.4700 205.8860 0.4268 31.8216 -31.5880
6.4800 206.2043 0.1099 31.8216 -31.6860
6.4900 206.5225 -0.2079 31.8216 -31.7840
R= 206.6326516782168
H= 51.652186492147095
T= 6.493462111822251
Rsim= 206.5224815819093
Hsim= 51.493204487290384
Tsim= 6.489999999999906
Graph
The accuracy of the simulation depends on the value of h(time step). With decreaing h, the accuracy will
increase.
275
Here the program has been modified using the following function
Script file
Program_132.py
1 from pylab import* #import module that help to work with arrays and plotting
2
3 def f1(t,x,ux): #Define function f1, which is x component of accelaration
4 return(0)
5 def f2(t,y,uy): #Define function f2, which is y component of accelaration
6 return(-9.8)
7 def f3(t,x,ux): #Define function f3, which is x component of velocity
8 return(ux)
9 def f4(t,y,uy): #Define function f4, which is y component of velocity
10 return(uy)
11
12 u=float(input('Enter the value of initial velocity, u(m/s):'))
13 theta=float(input('Enter the value of angle of projection:'))
14 rtheta=theta/57.3 #convert the angle into degree from radians or
15 radians(theta)
16 h=float(input('Enter time step:'))
17
18 x=0 #set initial value of x
19 y=0 #set initial value of y
20 t=0 #initial time
21
22 ax=0 #horizontal component of acce
23 ay=-9.8 #vertical component of acce, -ve because direction is opposite to g
24
25 ux=u*cos(rtheta) #x-component of initial velocity
26 uy=u*sin(rtheta) #y-component of initial velocity
27
28 xdata=[] #null list to store simulated x values
29 ydata=[] #null list to store simulated y values
30 tdata=[] #null list to store simulated t values
31
32 print(' t ',' x ',' y ',' ux ',' uy ')
33 while y>=0: #run loop till y=0, means the object touch the ground at y=0
34 ux=ux+h*f1(t,x,ux) #x-component of velocity using Euler's method
35 uy=uy+h*f2(t,y,uy) #y-component of velocity using Euler's method
36 x=x+h*f3(t,x,ux) #Genereated x coordinate
37 y=y+h*f4(t,y,uy) #Generated y coordinate
38 t=t+h #increment time
276
39 xdata.append(x) #store x value in null list named xdata
40 ydata.append(y) #store y value in null list named ydata
41 tdata.append(t)
42 print('%2.4f %7.4f %7.4f %7.4f %7.4f'%(t,x,y,ux,uy)) #formatted print
43 statement
44 g=9.8 # acceleration due to gravity
45 R=u**2*sin(2*rtheta)/g # Theoretical value of Range, R
46 H=u**2*sin(rtheta)**2/(2*g) # Theoretical value of Height, H
47 T=2*u*sin(rtheta)/g # Theoretical value of time of flight, T
48 print('R=',R)
49 print('H=',H)
50 print('T=',T)
51
52 Rsim=max(xdata) # Simulated value of Range,R
53 Hsim=max(ydata) # Simulated value of Height, H
54 Tsim=max(tdata) # Simulated value of Time of flight, T
55 print('Rsim=',Rsim)
56 print('Hsim=',Hsim)
57 print('Tsim=',Tsim)
58
59 plot(xdata,ydata,'r*')
60 xlabel('Horizontal distance,x')
61 ylabel('Vertical distance,y')
62 title('Projectile motion')
63 grid()
64 show()
Output
IDLE Shell 3.10.4
>> Enter the value of initial velocity, u(m/s):45
Enter the value of angle of proejection:45
Enter time step:0.01
Output
t x y ux uy
0.0100 0.3182 0.3172 31.8216 31.7200
0.0200 0.6364 0.6334 31.8216 31.6220
0.0300 0.9546 0.9487 31.8216 31.5240
0.0400 1.2729 1.2629 31.8216 31.4260
0.0500 1.5911 1.5762 31.8216 31.3280
0.0600 1.9093 1.8885 31.8216 31.2300
0.0700 2.2275 2.1998 31.8216 31.1320
0.0800 2.5457 2.5102 31.8216 31.0340
0.0900 2.8639 2.8195 31.8216 30.9360
---------------------------------------------------------
---------------------------------------------------------
6.4100 203.9767 2.3074 31.8216 -31.0000
6.4200 204.2950 1.9964 31.8216 -31.0980
6.4300 204.6132 1.6844 31.8216 -31.1960
6.4400 204.9314 1.3715 31.8216 -31.2940
6.4500 205.2496 1.0576 31.8216 -31.3920
277
6.4600 205.5678 0.7427 31.8216 -31.4900
6.4700 205.8860 0.4268 31.8216 -31.5880
6.4800 206.2043 0.1099 31.8216 -31.6860
6.4900 206.5225 -0.2079 31.8216 -31.7840
R= 206.6326516782168
H= 51.652186492147095
T= 6.493462111822251
Rsim= 206.5224815819093
Hsim= 51.493204487290384
Tsim= 6.489999999999906
Graph
The accuracy of the simulation depends on the value of h(time step). With decreaing h, the accuracy will
increase.
278
Here the simulation is to check how many number of nuclei in the given sample undergo radioactive
decay after a particular period of time, i.e., time vs number of nuclei remaining in the sample after a
certain time interval.
Consider a sample consisting of N (N should be a large number, lets say 10,000) nuclei out of which
some may undergo radioactive decay and some may not. Let this radioactive decay property is denoted
using a probability, i.e., if the probability is 1, the nuclei definitely undergo decay, if the probability is
0, then it will not and it the probability is 0.5, it may or may not undergo decay. For certainty, assume
that if the probability P is greater than 0.9, then the nuclei will definitely decay in the given period of
time. Using random.random array function (generate a random 0 and 1 number between) in the numpy
module, apply a random probability to N number of nuclei. Count the total number of nuclei have
probability greater than 0.9 out of the N number of nuclei. Subtract this number from N and again apply
probability to the remaining nuclei. Repeat the same process until the remaining number of nuclei in
the sample is equal to a small value lets say 100. Such a computational algorithms that rely on repeated
random sampling to obtain numerical results is known as Monte Carlo simulation Method. Lets take
any unstable nuclei by assuming that it have random probability of decay which is between 0 and 1
which can be denoted using the equation
𝑁=𝑁 𝑒
i.e., the rate of decay is proportional to the number of nuclei present in the sample.
Script file
Program_132.py
1 import pylab as pl
2 import numpy as np
3
4 N=100000 #intial number of radioactive nuclei
5 t=0 #time at which simulation star
6 ndata=[N]#to store the remaining number of nuclei after every instant of time
7 tdata=[t] #store incremented time
8 while N>=100: #run the simulation till 100 nuclei left
9 p=np.random.random(N) #generate N number of random numbers
10 for i in p: #take each random number out of N one by one
11 if i>0.6: #if random number value is >0.6, assume it is decayed
12 N=N-1 #if it is decayed, decrement the value of N by one
13 t=t+1 # increment time
14 ndata.append(N) # when the for loop complete, store the remaining no of
15 nuclei in ndata
16 tdata.append(t)
17 pl.plot(tdata,ndata,'r')
18 pl.xlabel('Time')
19 pl.ylabel('Number of Nuclei,N')
20 pl.title('Monte Carlo Simulation:Radioactivity')
279
21 y=ndata[0]*np.exp(-0.6*np.array(tdata)) #plotting theoretical value
22 pl.plot(tdata,y,'*b')
23 pl.legend(['simulation','Theory'])
24 pl.grid()
25 pl.show()
Graph
280
>>>l.sort()
>>>print(l)
[1, 2, 4, 5, 6]
>>>l[::-1]
[6, 5, 4, 2, 1]
Or
>>>l.reverse()
>>>print(l)
[6, 5, 4, 2, 1]
5. Which are the numerical data types allowed in python (2 mark)
Ans:Integer, eg: 12
Long integer, eg:7L
Floating, eg: -7.2
Octal, eg: 0o23
Hexadecimal, eg:0x12
Complex, eg:2+3j
6. Write the output of the following code (2 mark)
for i in range(10):
if i%2==0:
print(i)
Ans:
0
2
4
6
8
Explanation: % is the modulus operator which returns remainder, here i will print when the
reminder matches zero. range(10) returns elements 0,1,2,3,4,5,6,7,8,9. Here only even number
has remainder zero when divide with 2
7. With suitable example, explain any five list operations (5 mark)
Ans:
Lets take a list;
Examples of list operations are append(), insert, index(), len(), remove(),pop()
>>>list1=[1,3,10.5,’apple’,1,3,1,-5]
>>>list.append(‘orange’)
>>>print(list1)
[1,3,10.5,’apple’,1,3,1,-5,’orange’]
>>>list1.insert(3,'mango')
>>>print(list1)
[1, 3, 10.5, 'mango', 'apple', 1,3, 1, -5, 'orange']
>>>len(list1)
12
281
>>>list1.index(10.5)
2
>>>list1.remove(10.5)
>>>print(list1)
[1, 3, 'mango', 'apple', 1, 3, 1,-5, 'orange', (-2+3j), 22.2]
>>>list1.pop(1)
3
>>>print(list1)
[1, 10.5, 'mango', 'apple', 1, 3, 1, -5, 'orange', (-2+3j), 22.2
8. Write an algorithm to accept two numbers compute the sum and print the result. (2 mark)
Ans
1. Enter the first number using int(input()) statement assigning it to a variable ‘a’
2.Enter the second number using int(input()) statement assigning it to a variable ‘b’
3. Add a and b and assign it to a variable c, c=a+b
4. print c
9. What is the difference between a compiler and interpreter in a computer? (2 mark)
Ans : Read chap-1 note
10. Name the different data types in Python. (2 mark)
Ans: Read chap-1 note
11. What will be the output of the program? (2 mark)
>>> a = 4.0
>>> x = 3.0
>>> y = (x+ a/x)/2
Ans:y=(3.0+(4.0/3.0))/2=2.16666
y=(3+1.33333)/2
y=4.333333/2=2.16666
12. What is a tuple? How literals of type tuple are written? Give example. (2 mark)
Ans:Read chap-1 note
13. What is a list? How lists are different from tuples? (2 mark)
Ans:Read chap-1 note
14. (a)Write the syntax for the control statements if..elif...if and while in Python.
b) Write a program that tests whether a number is prime or not using while and if...else (5 mark)
Ans: (a) Read chap-1 note
(b)Prime numbers cannot be divide by any other number except itself and one. If n is a
prime number then it cannot be divided by any number from 2 to n-1.
Eg. 3/1=3: 3/3=1, it cannot be divided with any other number
Eg of prime numbers are 2,3,5,7,11,..
Program
num = int(input("Enter a number ( greater than 1)"))
f = 0
i = 2
while i <= num / 2:
if num % i == 0:
f=1
break
i=i+1
if f==0:
282