0% found this document useful (0 votes)
33 views13 pages

Python Lab - Ipynb - Colaboratory

The document discusses Python concepts like loops, functions, conditionals, plotting graphs, differentiation, integration and Laplace transforms. It contains examples and code snippets to demonstrate these concepts. Various mathematical functions and their derivatives are evaluated. Integrals of functions are also calculated. Laplace transforms of functions are determined.

Uploaded by

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

Python Lab - Ipynb - Colaboratory

The document discusses Python concepts like loops, functions, conditionals, plotting graphs, differentiation, integration and Laplace transforms. It contains examples and code snippets to demonstrate these concepts. Various mathematical functions and their derivatives are evaluated. Integrals of functions are also calculated. Laplace transforms of functions are determined.

Uploaded by

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

10/8/23, 7:25 PM Python Lab.

ipynb - Colaboratory

Loops

from numpy import *


print(arange(1,11))
sum = 0
for i in arange(1,11):
sum = sum+i
print(sum)
print(sum)

[ 1 2 3 4 5 6 7 8 9 10]
1
3
6
10
15
21
28
36
45
55
55

from numpy import *


arange(1,11)
for i in (arange(1,11)):
print(2,'X',i ,'=', 2*i)

2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20

from numpy import *


a = int(input("Enter the number : "))
i=1
while i<=10:
print(a,'x',i,'=',a*i)
i = i+1

Enter the number : 10


10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Program to check whether the given integer is divisible by 3

n = int(input("Enter the number: "))


if n%3 == 0:
print("The given number is divisible by 3")
else:
print("n is not divisible by 3")

Enter the number: 27


The given number is divisible by 3

Given m,x and n. Write a program to check wether x lies between m and n

m,n,x = input("Enter the value of m n and x: ").split()

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 2/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory
if m<x<n:
print("X lies between m and n")
else:
print("X doesnot lie between m and n")

Enter the value of m n and x: 19 27 30


X doesnot lie between m and n

Given two numbers m and n. Write a program to print "HI" either m or n greater than 5
else print "Bye"

m = float(input("Enter the value of m: "))


n = float(input("Enter the value of n: "))
if m>5 or n>5:
print("Hi")
else:
print("Bye")

Enter the value of m: 33


Enter the value of n: 55
Hi

Create a function to find sum of two numbers and product of two numbers

def add(x,y):
z=x+y
print(z)

def mul(u,v):
w=u*v
print(w)

import numpy
print(dir(numpy))
import math
print(dir(math))

['ALLOW_THREADS', 'AxisError', 'BUFSIZE', 'CLIP', 'ComplexWarning', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_IGNORE', 'ERR_LOG
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil'

By importing math module find the value of sin (90)

from math import *


print(sin(pi/4))

0.7071067811865475

from math import *


print(cos(pi))

-1.0

Find the value of f(x) =

import sympy as sp
x = sp.symbols(x)
f= x**2+x-2
print(f.subs(x,5))

28

import sympy as sp
x,y = sp.symbols('x y')
f= x**2+y**2-(2*x*y)
print(f.subs(x,1).subs(y,-1))

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 3/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory

Plot the function f(x) = sin(x) and f(x) = cos(x) in the interval (-10,10)

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-10,10,500)
f1=np.sin(x)
f2 =np.cos(x)
plt.plot(x,f1)
plt.plot(x,f2)

[<matplotlib.lines.Line2D at 0x78b22cc107f0>]

Plot the function y = x2 and y = x1/2 in the interval (-10,10)

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,1.2,500)
y1=x**2
y2=x**(1/2)
plt.plot(x,y1,linestyle='--')
plt.plot(x,y2,linestyle='--')
plt.show()

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,1,500)
y1=x**2
y2=x**(1/2)
plt.plot(x,y1,linestyle='--')
plt.plot(x,y2,linestyle='--')
plt.show()

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 4/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,0.5,500)
y1=x**2
y2=x**(1/2)
plt.plot(x,y1,linestyle='--')
plt.plot(x,y2,linestyle='--')
plt.show()

import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(0,1.2,500)
y1=x**2
y2=x**(1/2)
plt.plot(x,y1,color='r',linestyle='--',label='y1=x**2')
plt.plot(x,y2,color='m',linestyle='-.',label='y1=x**(1/2)')
plt.legend()
plt.title('Plots of y=x^2 and y=x^1/2')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.fill_between(x,y1,y2,color='g')
plt.grid()
plt.show()

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 5/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory

Differentation and Integration

1.Find the derivative of the following

from sympy import *


x = symbols('x')
y = sin(x)
dy=diff(y)
print('Derivative of',y,'is',dy)

Derivative of sin(x) is cos(x)

from sympy import *


x = symbols('x')
y = cos(x)
dy= diff(y)
print("Derivative of",y,"is",dy)

Derivative of cos(x) is -sin(x)

from sympy import*


x = symbols('x')
y = tan(x)
dy = diff(y)
print("Derivative of",y,"is",dy)

Derivative of tan(x) is tan(x)**2 + 1

from sympy import*


x,y = symbols('x y')
f = sin((2*x)+(3*y))
dfx = diff(f,x)
print("Derivative of",f,"w.r.t",x,"is",dfx)
dfy = diff(f,y)
print("Derivative of",f,"w.r.t",y,"is",dfy)

Derivative of sin(2*x + 3*y) w.r.t x is 2*cos(2*x + 3*y)


Derivative of sin(2*x + 3*y) w.r.t y is 3*cos(2*x + 3*y)

from sympy import*


x,y = symbols('x y')
f = sin((2*x)+(3*y))
dfxx = diff(f,x,2)
print(" Partial Derivative of",f,"w.r.t",x,"is",dfxx)
dfyy = diff(f,y,2)
print("Partial Derivative of",f,"w.r.t",y,"is",dfyy)
dfxy = diff(diff(f,x),y)
print("Partial Derivative of",f,"w.r.t", x and y,"is",dfxy)

Partial Derivative of sin(2*x + 3*y) w.r.t x is -4*sin(2*x + 3*y)


Partial Derivative of sin(2*x + 3*y) w.r.t y is -9*sin(2*x + 3*y)
Partial Derivative of sin(2*x + 3*y) w.r.t y is -6*sin(2*x + 3*y)

At (pi/4,0)

from sympy import*


x,y = symbols('x y')
f = sin((2*x)+(3*y))
dfxx = diff(f,x,2)
d1 = dfxx.subs({x:pi/4,y:0})

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 6/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory
print(" Partial Derivative of",f,"w.r.t",x,"at point (pi/4,0)is",d1)
dfyy = diff(f,y,2)
d2 = dfyy.subs({x:pi/4,y:0})
print("Partial Derivative of",f,"w.r.t",y,"at point (pi/4,0)is",d2)
dfxy = diff(diff(f,x),y)
d3 = dfxy.subs({x:pi/4,y:0})
print("Partial Derivative of",f,"w.r.t", x and y,"is",d3)

Partial Derivative of sin(2*x + 3*y) w.r.t x at point (pi/4,0)is -4


Partial Derivative of sin(2*x + 3*y) w.r.t y at point (pi/4,0)is -9
Partial Derivative of sin(2*x + 3*y) w.r.t y is -6

Find the integration of the following functions


1. f = cosx

2. f = logx

3. f = x
3

4. f = 1/1 + x
2

from sympy import *


x = symbols('x')
f1 = cos(x)
intf1=integrate(f1,x)
print("Integration of",f1,"is",intf)

Integration of cos(x) is sin(x)

from sympy import *


x = symbols('x')
f2 = log(x)
intf2=integrate(f2,x)
print("Integration of",f2,"is",intf2)

Integration of log(x) is x*log(x) - x

from sympy import *


x = symbols('x')
f3 = x**3
intf3=integrate(f3,x)
print("Integration of",f3,"is",intf3)

Integration of x**3 is x**4/4

π/2
Evaluate ∫0 cos xdx

from sympy import *


x = symbols('x')
f4 = cos(x)
intf4=integrate(f4,(x,0,pi/2))
print("Integration of",f4,"is",intf4)

Integration of cos(x) is 1

2 1
Evaluate ∫0 ∫
0
xydxdy

from sympy import*


x,y = symbols('x y')
f5=x*y
intf5=integrate(f5,(x,0,1),(y,0,2))
print(intf5)

Laplace and inverse Laplace Transforms


Find the laplace transform of the following function

1. f (t) = e
(2t)

2. f (t) = sint

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 7/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory
3. f (t) = t
(3)
+ e
(−1)
+ cost

from sympy import *


t,s = symbols('t s')
f= exp(2*t)
LT = laplace_transform(f,t,s)
print(LT)

(1/(s - 2), 2, True)

from sympy import *


t,s = symbols('t s')
f= sin(a*t)
LT = laplace_transform(f,t,s)
print(LT)

(a/(a**2 + s**2), 0, True)

from sympy import *


t,s = symbols('t s')
f= t**3+exp(-1)+cos(t)
LT = laplace_transform(f,t,s)
display(LT)

(s/(s**2 + 1) + exp(-1)/s + 6/s**4, 0, True)

Find the inverse laplace transform of

1. F (s) =
s−1
4

2. F (s) =
2
1

(s −1)(s+1)

3. F (s) =
s−1
1
+
4
2
s

from sympy import *


from sympy.integrals import inverse_laplace_transform
s,t = symbols('s t',positive=true)
F = (4)/(s-1)
ILT=inverse_laplace_transform(F,s,t)
print(ILT)

4*exp(t)

from sympy import *


from sympy.integrals import inverse_laplace_transform
s,t = symbols('s t',positive=true)
F=1/((s**2-1)*(s+1))
x=inverse_laplace_transform(F,s,t)
print(x)

(-2*t + exp(2*t) - 1)*exp(-t)/4

from sympy import *


from sympy.integrals import inverse_laplace_transform
s,t = symbols('s t',positive=true)
F=(1/(s-1))+(4/(s+1))
x=inverse_laplace_transform(F,s,t)
print(x)

exp(t) + 4*exp(-t)

from sympy import *


M = Matrix([[1,2,3,4],[0,2,4,5],[0,0,5,6]])
display(M)

⎡1 2 3 4⎤
0 2 4 5
⎣0 6⎦
​ ​ ​ ​ ​ ​

0 5

from sympy import *


M = Matrix([[1,2,3,4],[0,2,4,5],[0,0,5,6]])
display(M)
[m,n]= shape(M)
print('Size of the matrix M is',m,'X',n)

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 8/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory

⎡1 2 3 4⎤
0 2 4 5
⎣0 6⎦
​ ​ ​ ​ ​ ​

0 5
Size of
from sympy the matrix
import * M is 3 X 4
M = Matrix([[1,2,3],[2,4,5],[0,5,6]])
display(M)
[m,n]= shape(M)
print('Size of the matrix M is',m,'X',n,'\n')
B=M.rref( )
print('Row reduced Echelon form of M is\n\n')
pprint(B)
display('Rank of the matrix M is',M.rank())
print('|M|=',det(M))
print('Trace of M is',trace(M))
print('Inverse if M is\n')
display(M.inv())

⎡1 2 3⎤
2 4 5
⎣0 6⎦
​ ​ ​ ​ ​

5
Size of the matrix M is 3 X 3

Row reduced Echelon form of M is

⎛⎡1 0 0⎤ ⎞
⎜⎢ ⎥ ⎟
⎜⎢0 1 0⎥, (0, 1, 2)⎟
⎜⎢ ⎥ ⎟
⎝⎣0 0 1⎦ ⎠
'Rank of the matrix M is'
3
|M|= 5
Trace of M is 11
Inverse if M is

⎡ −5 − 25 ⎤
1 3
5
​ ​ ​

− 12 6 1
⎣ 2 0 ⎦
5 5 5
​ ​ ​ ​ ​ ​ ​ ​

−1

from sympy import *


M = Matrix([[1,2,3],[2,4,5],[4,8,11]])
print('Find the inverse of the matrix')
display(M)
print('Inverse of the matris is')
display(M.inv())

Find the inverse of the matrix


⎡1 2 3⎤
2 4 5
⎣4 11⎦
​ ​ ​ ​ ​

8
Inverse of the matris is
---------------------------------------------------------------------------
NonInvertibleMatrixError Traceback (most recent call last)
<ipython-input-47-0c8cc85fb958> in <cell line: 6>()
4 display(M)
5 print('Inverse of the matris is')
----> 6 display(M.inv())

3 frames
/usr/local/lib/python3.10/dist-packages/sympy/matrices/inverse.py in _inv_GE(M, iszerofunc)
243
244 if any(iszerofunc(red[j, j]) for j in range(red.rows)):
--> 245 raise NonInvertibleMatrixError("Matrix det == 0; not invertible.")
246
247 return M._new(red[:, big.rows:])

NonInvertibleMatrixError: Matrix det == 0; not invertible.

SEARCH STACK OVERFLOW

from sympy import *


M = Matrix([[1,2,3],[2,4,5],[4,8,11]])
print('Extract [1,2] from the matrix')
display(M)
display(M[0,0:2])
display(M[1:,2])
display(M[0,0:])
display(M[1,0:])
display(M[2,0:])
display(M[0:,0])

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 9/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory
display(M[0:1:2,2])
display(M[1:,0:2])

Extract [1,2] from the matrix


⎡1 2 3⎤
2 4 5
⎣4 8 11⎦
​ ​ ​ ​ ​

[1 2] ​ ​

5
[ ]
11

[1 2 ​ ​ 3] ​

[2 4 ​ ​ 5] ​

[4 8 11]
⎡1⎤
​ ​ ​

2
⎣4⎦
​ ​ ​

[3] ​

2 4
[ ]
4 8
​ ​

Consider the matrix


2 1 0
⎡ ⎤
A = ⎢1 2 0⎥
⎣ ⎦
0 0 1

Then find

1.Inverse of A

2.Eigen values and eigen vectors of a

from sympy import *


m=Matrix([[2,1,0],[1,2,0],[0,0,1]])
display(m)
print("Inverse of matrix M is:")
im=m.inv()
display(im)
eval=m.eigenvals()
print("The eigen values of the matrix are\n")
display(eval)
evects=m.eigenvects()
print("The eigen vectors of the matrix are\n\n")
pprint(evects)

⎡2 1 0⎤
1 2 0
⎣0 1⎦
​ ​ ​ ​ ​

0
Inverse of matrix M is:
⎡ 0⎤
2
3

− 13 ​

− 13 2
0
⎣ 0 1⎦
3
​ ​ ​ ​ ​ ​

0
The eigen values of the matrix are

{3: 1, 1: 2}
The eigen vectors of the matrix are

⎡⎛ ⎡⎡-1⎤ ⎡0⎤⎤⎞ ⎛ ⎡⎡1⎤⎤⎞⎤


⎢⎜ ⎢⎢ ⎥ ⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥⎥⎟⎥
⎢⎜1, 2, ⎢⎢1 ⎥, ⎢0⎥⎥⎟, ⎜3, 1, ⎢⎢1⎥⎥⎟⎥
⎢⎜ ⎢⎢ ⎥ ⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥⎥⎟⎥
⎣⎝ ⎣⎣0 ⎦ ⎣1⎦⎦⎠ ⎝ ⎣⎣0⎦⎦⎠⎦

from sympy import *


m=Matrix([[2,3,0,0],[2,3,0,0],[0,0,2,3],[0,0,2,3]])
display(m)
a=m.eigenvals()
print("The eigen values of the matrix are\n")
display(a)
b=m.eigenvects()
print("The eigen vectors of the matrix are\n\n")
pprint(b)

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 10/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory

⎡2 3 0 0⎤
2 3 0 0
0 0 2 3
⎣0 3⎦
​ ​ ​ ​ ​ ​

0 2
The eigen values of the matrix are

{5: 2, 0: 2}
The eigen vectors of the matrix are

⎡⎛ ⎡⎡-3/2⎤ ⎡ 0 ⎤⎤⎞ ⎛ ⎡⎡1⎤ ⎡0⎤⎤⎞⎤


⎢⎜ ⎢⎢ ⎥ ⎢ ⎥⎥⎟ ⎜ ⎢⎢ ⎥ ⎢ ⎥⎥⎟⎥
from sympy
⎢⎜ import
⎢⎢ 1 *⎥ ⎢ 0 ⎥⎥⎟ ⎜ ⎢⎢1⎥ ⎢0⎥⎥⎟⎥
m=Matrix([[2,3],[1,2]])
⎢⎜0, 2, ⎢⎢ ⎥, ⎢ ⎥⎥⎟, ⎜5, 2, ⎢⎢ ⎥, ⎢ ⎥⎥⎟⎥
display(m)
⎢⎜ ⎢⎢ 0 ⎥ ⎢-3/2⎥⎥⎟ ⎜ ⎢⎢0⎥ ⎢1⎥⎥⎟⎥
⎢⎜
print("Inverse⎢⎢ of matrix
⎥ ⎢ M⎥⎥⎟ ⎜
is:") ⎢⎢ ⎥ ⎢ ⎥⎥⎟⎥
⎣⎝
im=m.inv() ⎣⎣ 0 ⎦ ⎣ 1 ⎦⎦⎠ ⎝ ⎣⎣0⎦ ⎣1⎦⎦⎠⎦
display(im)
eval=m.eigenvals()
print("The eigen values of the matrix are\n")
display(eval)
evects=m.eigenvects()
print("The eigen vectors of the matrix are\n\n")
pprint(evects)

2 3
[ ]
1 2
​ ​

Inverse of matrix M is:


2 −3
[ ]
−1 2
​ ​

The eigen values of the matrix are

{2 - sqrt(3): 1, sqrt(3) + 2: 1}
The eigen vectors of the matrix are

⎡⎛ ⎡⎡-√3⎤⎤⎞ ⎛ ⎡⎡√3⎤⎤⎞⎤
⎢⎜2 - √3, 1, ⎢⎢ ⎥⎥⎟, ⎜√3 + 2, 1, ⎢⎢ ⎥⎥⎟⎥
⎣⎝ ⎣⎣ 1 ⎦⎦⎠ ⎝ ⎣⎣1 ⎦⎦⎠⎦

Solve the system of equations


x + y − 2z = 1

x + y + 4z = 1

2x + 2y + 8z = 2

from sympy import solve


from sympy.abc import x, y, z
equations = [x +y-2*z-1,x+y+4*z-1,2*x+2*y+8*z-2]
sol=solve(equations,x,y,z)
display(sol)

{x: 1 - y, z: 0}

By Gauss Siedel method

x=0;y=0;z=0
for i in range(1,20):
x=1-y+2*z
y=1-x-4*z
z=(2-2*y-2*x)/8
display(x,y,z)

1.0
0.0
0.0

from sympy import solve


from sympy.abc import x, y, z
equations = [x +2*y+z-1,2*x+y-z-2,x-3*y+z-4]
sol=solve(equations,x,y,z)
display(sol)

{x: 8/5, y: -3/5, z: 3/5}

Newton's Forward Interpolation

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 11/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory
from numpy import *
x = [1,2,3,4,5]
y = [10,20,30,50,80]
m=float(input('enter the value of x: '))
n=len(x)-1
h=x[1]-x[0]
sum = y[-1]
t = (m-x[-1])/h
prod = 1
for i in range(0,n):
y = diff(y)
print(y)
prod = prod*(t+i)/(i+1)
sum = sum + prod*y[-1]
print('by NFI value of y(',m,')=',sum)

enter the value of x: 2


[10 10 20 30]
[ 0 10 10]
[10 0]
[-10]
by NFI value of y( 2.0 )= 20.0

Simpson's 1/3

from numpy import *


a = 0
b = 1
n = 8 # n should be multipal of 2
h = (b-a) /n
x = linspace(a,b,n+1)
f = sin(x**2)
I = (h/3) * (f[0] + f[-1] + 4*sum(f[1:n:2]) + 2*sum(f[2:n:2]))
print('approximate value of given I is ',I)

approximate value of given I is 0.31024853238818184

Simpson's 3/8

from numpy import *


a = 0
b = 1
n = 6 # n should be multipal of 3
h = (b-a) /n
x = linspace(a,b,n+1)
f = sin(x**2)
I = (3*h/8) * (f[0] + f[-1] + 3*sum(f[1:n]) - sum(f[3:n:3]))
print('approximate value of given I is ',I)

approximate value of given I is 0.31012465182031024

Runge Kutta 4th Order

from numpy import *


x0=0; y0=1; xn=0.4; h=0.1;
n=round((xn-x0)/h)
def f(x,y):
return (y**2-x**2)/(x**2+y**2)
for i in range(0,n):
k1 = h*f(x0,y0)
k2 = h*f(x0+h/2,y0+k1/2)
k3 = h*f(x0+h/2,y0+k2/2)
k4 = h*f(x0+h,y0+k3)
y = y0+1/6*(k1+2*k2+2*k3+k4)
print("Approximate solution at y(%0.2f) is %0.4f"%(x0+h,y))
y0 = y
x0 = x0 + h

Approximate solution at y(0.10) is 1.0994


Approximate solution at y(0.20) is 1.1960
Approximate solution at y(0.30) is 1.2882
Approximate solution at y(0.40) is 1.3753

Euler's Modified Method

from numpy import *


x0=0;y0=1;h=0.1;xn=0.6

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 12/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory
n= round((xn-x0)/h)
def f(x,y):
return sin(x*y)
for i in range(0,n):
y1p=y0+h*f(x0,y0)
for j in range(1,50):
y1c=y0+h/2*(f(x0,y0)+f(x0+h,y1p))
if abs(y1c-y1p<10**(-4)):
print("The approx. soln. after %d iteration is y(%f)=%f"%(j,x0+h,y1c))
break
y1p=y1c
x0=x0+h
y0=y1c

The approx. soln. after 2 iteration is y(0.100000)=1.005017


The approx. soln. after 2 iteration is y(0.200000)=1.020164
The approx. soln. after 2 iteration is y(0.300000)=1.045723
The approx. soln. after 2 iteration is y(0.400000)=1.082124
The approx. soln. after 3 iteration is y(0.500000)=1.129865
The approx. soln. after 3 iteration is y(0.600000)=1.189362

Linear Curve Fitting

from numpy import *


import matplotlib.pyplot as plt
x=array([1,2,3,4,5])
y=array([2.1,3.9,6.2,8.1,9.8])
p=polyfit(x,y,1)
print(p)
print('linear fit is y= %0.3f*x+%0.3f'%(p[0],p[1]))
t=linspace(1,5,50)
z=p[0]*t+p[1]
plt.plot(t,z,"r",label="linear fit")
plt.scatter(x,y,label="Data")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()

[1.96 0.14]
linear fit is y= 1.960*x+0.140

from numpy import *


from matplotlib.pyplot import *
mean = 0
std_dev = 1
num_samples = 1000
random_numbers = random.normal(mean,std_dev,num_samples)
hist(random_numbers, density = True, color = 'g', label = 'random numbers')
xmin,xmax = xlim()
x = linspace(xmin,xmax,100)
p = exp(-0.5*((x-mean)/std_dev)**2)/(std_dev * sqrt(2*pi))
plot(x,p,'--',linewidth = 2,label = 'PDF')
xlabel('value')
ylabel('Probability')
title('Normal distribution')
legend()

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 13/14
10/8/23, 7:25 PM Python Lab.ipynb - Colaboratory

<matplotlib.legend.Legend at 0x7f1cb13bfe50>

https://colab.research.google.com/drive/156XP9PLhm4zuxCNCON6B6PTvcy7AZ2N7?authuser=2#scrollTo=PxycL_k1Tcf4&printMode=true 14/14

You might also like