0% found this document useful (0 votes)
7 views

Final Lab Manual Python (2)

The document is a record of practical work conducted by a student in the Physics Laboratory at Loyola College, detailing various experiments in Computational Physics and Workshop Technology. It includes a list of Python programming tasks such as arithmetic operations, arrays, and matrices, as well as workshop tasks like shaping and welding. Each experiment outlines the aim, code examples, and outputs obtained from the programs.

Uploaded by

msgokul0007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Final Lab Manual Python (2)

The document is a record of practical work conducted by a student in the Physics Laboratory at Loyola College, detailing various experiments in Computational Physics and Workshop Technology. It includes a list of Python programming tasks such as arithmetic operations, arrays, and matrices, as well as workshop tasks like shaping and welding. Each experiment outlines the aim, code examples, and outputs obtained from the programs.

Uploaded by

msgokul0007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

DEPARTMENT OF PHYSICS

LOYOLA COLLEGE (Autonomous)

NUNGAMBAKKAM, CHENNAI – 600 034.

Dept. No.
Certified Bonafide Record of Practical work done
by Mr………………………………………………in the physics
Laboratory, Loyola College, Chennai -34, during the Academic
year .........................

___________
Professor

Submitted for the Practical Examination held on …………………………

Examiners:
1.

2.
TABLE OF CONTENTS

Expt. No Name of the experiment Marks Staff Signature

1.

2.

3.

4.

5.

6.

7.

8.

Professor
UPH 6705 COMPUTATIONAL PHYSICS AND WORKSHOP
TECHNOLOGY

COMPUTATIONAL PHYSICS
List of Experiments:
1. Python programming – simple arithmetic operations I
2. Python programming – simple arithmetic operations II
3. Python programming – arrays
4. Python programming – matrices
5. Python programming – solving differential equations
6. Python programming – Trapezoidal and Simpson Rule
7. Python programming – Lagrange’s interpolation method
8. Programming – Newton’ Raphson method Python

WORKSHOP TECHNOLOGY
List of Experiments:
9. Shaping to the planned dimensions.
10. Cutting and bending.
11. Using drilling machines for various requirements.
12. Different types of welding.
13.Boxes of different sizes.
14. Wood work.
15. Experiments using lathe.
16.House wiring.
COMPUTATIONAL PHYSICS
1. Python Programming – Simple Arithmetic
Operations I
Aim:
To write, enter and execute a python program to perform simple arithmetic
operations.

ARITHMETIC OPERATION:
1. To execute the simple arithmetic operations.
num1 = float(input("enter the first number"))
num2 = float(input("enter the second number"))
# Add two numbers
sum = float(num1) + float(num2)
# Subtract two numbers
diff = float(num1) - float(num2)
# Multiply two numbers
prod = float(num1) * float(num2)
#Divide two numbers
div = float(num1) / float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
# Display the subtraction
print('The subtraction of {0} and {1} is {2}'.format(num1, num2, diff))
#Display the multiplication
print('The multiplication of {0} and {1} is {2}'.format(num1, num2, prod))
# Display the division
print('The division of {0} and {1} is {2}'.format(num1, num2, div))
Output
Enter the first number4
Enter the second number5

The sum of 4.0 and 5.0 is 9.0


The subtraction of 4.0 and 5.0 is -1.0
The multiplication of 4.0 and 5.0 is 20.0
The division of 4.0 and 5.0 is 0.8

2. (i) To find the square of a no: (By declaring a number)


# Input numbers:
# Declaring the number.
n =4
# Finding square by multiplying them with each other
square =n *n
# Printing square
print(square)

Output:

16

(ii) By getting the input from the user.


n= float(input("enter a number"))
# Finding square by using exponent operator
# This will yield n power 2 i.e. square of n
square =n**2
# Printing square
print ("Square of {0} is {1} ".format (n, square))
Output:
enter a number5
Square of 5.0 is 25.0
(iii) Using pow in built function
# Declaring the number.
n =4
# Finding square by using pow method
# This will yield n power 2 i.e. square of n
square =pow (n, 2)
# Printing square
print(square)

Output:
16.0

3. To find the square root of a number


# sqrt() method
# import the math module
import math
# print the square root of 0
print(math.sqrt(0))
# print the square root of 4
print(math.sqrt(4))
# print the square root of 3.5
print(math.sqrt(3.5))

Output:
0.0
2.0
1.8708286933869
4. To calculate the sum of the digits

#Sum of the digits:


n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print("The total sum of digits is:",tot)

Output:
Enter a number 45
The total sum of digits is: 9

Result:
The above programs have been entered and the required output was obtained.

Staff Signature
2. Python Programming – Simple Arithmetic Operations II
Aim:
To write, enter and execute a python program to perform simple
arithmetic operations.
1. To find the factorial of a number provided by the user
#Python program to find the factorial of a number provided by the
user.
#To take input from the user
# num = int(input(“Enter a number:”))
factorial = 1
#Check if the number is negative, positive ort zero
if num<0:
print(“ Factorial does not exist for negative numbers”)
elif num ==0:
print (“The factorial of 0 is 1”)
else:
for i in range(1,num+1):
factorial=factorial * i
print(“The factorial of “, num, “is”, factorial)

Output:

Enter a number 3
The factorial of 3 is 1
The factorial of 3 is 2
The factorial of 3 is 6
2. To find the largest among three numbers

# Python program to find the largest number among the three input numbers
# take three numbers from user
num1 =float(input("Enter first number: "))
num2 =float(input("Enter second number: "))
num3 =float(input("Enter third number: "))
if(num1 > num2)and(num1 > num3):
largest = num1
elif(num2 > num1)and(num2 > num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)

Output:

Enter the first number: 10

Enter the first number: 16

Enter the first number: 12

The largest number is 16.0

3. Using max() method to find the largest among a number in a list.


# Python program to find largest
# list of numbers
list1 =[10, 20, 4, 45, 99]
print("Largest element is:", max(list1))

Output:
Largest element is: 99
4. Using loops to find the largest among a number in a list.
# Python program to find largest
# number in a list
# creating empty list
list1 =[ ]
# asking number of elements to put in list
num =int(input("Enter number of elements in list: "))
# iterating till num to append elements in list
for i in range(1, num +1):
else =int(input("Enter elements: "))
list1.append(ele)
# print maximum element
print("Largest element is:", max(list1))

Output:
Enter number of elements in list: 4
Enter elements: 12
Enter elements: 19
Enter elements: 1
Enter elements: 99
Largest element is: 99

Result:
The above programs have been entered and the required output was obtained.

Staff Signature
3. Python Programming – Arrays
Aim:
To write, enter and execute a python program to perform simple operations in an
array.
1. To create an array

# Python program to demonstrate


# Creation of Array
# importing "array" for array creations
import array as arr
# creating an array with integer type
a =arr.array('i', [1, 2, 3])
# printing original array
print("The new created array is : ", end =" ")
for i in range(0, 3):
print(a[i], end =" ")
print()
# creating an array with float type
b =arr.array('d', [2.5, 3.2, 3.3])
# printing original array
print("The new created array is : ", end =" ")
for i in range(0, 3):
print(b[i], end =" ")
Output :
The new created array is : 1 2 3
The new created array is : 2.5 3.2 3.3
1. To add elements in an array
# Adding Elements to an Array
# importing "array" for array creations
import array as arr
# array with int type
a =arr.array('i', [1, 2, 3])
print("Array before insertion : ", end =" ")
for i in range(0, 3):
print(a[i], end =" ")
print()
# inserting array using insert() function
a. insert(1, 4)
print("Array after insertion : ", end =" ")
for i in(a):
print(i, end =" ")
print()
# array with float type
b =arr.array('d', [2.5, 3.2, 3.3])
print("Array before insertion : ", end =" ")
for i inrange(0, 3):
print(b[i], end =" ")
print()
# adding an element using append()
b.append(4.4)
print("Array after insertion : ", end =" ")
for i in(b):
print(i, end =" ")
print()
Output :
Array before insertion : 1 2 3
Array after insertion : 1 4 2 3
Array before insertion : 2.5 3.2 3.3
Array after insertion : 2.5 3.2 3.3 4.4

To sort the list in ascending order.

Syntax
# This will sort the given list in ascending order.
# It returns a sorted list according to the passed parameter.
List_name.sort()

This function can be used to sort list of integers, floating point number, string
and others.

# List of Integers
numbers =[1, 3, 4, 2]
# Sorting list of Integers
numbers.sort()
print(numbers)
# List of Floating point numbers
Decimal number =[2.01, 2.00, 3.67, 3.28, 1.68]
# Sorting list of Floating point numbers
Decimal number.sort()
print(decimalnumber)
# List of strings
words =["I ", "love", "loyola"]
# Sorting list of strings
words.sort()
print(words)

Output:
[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['I', 'love', 'loyola']
1. Python program to sort the elements of an array in ascending order

#Initialize array

arr = [5, 2, 8, 7, 1, 3, 13, 64, 23, 15, 48, 39, 9];

temp = 0;

#Displaying elements of original array

print("Elements of original array: ");

for i in range(0, len(arr)):

print(arr[i], end=" ");

#Sort the array in ascending order

for i in range(0, len(arr)):

for j in range(i+1, len(arr)):

if(arr[i] >arr[j]):

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

print();

#Displaying elements of the array after sorting

print("Elements of array sorted in ascending order: ");


for i in range(0, len(arr)):
print(arr[i], end=" ");

Output:
Elements of original array:
5 2 8 7 1 3 13 64 23 15 48 39 9
Elements of array sorted in ascending order:
1 2 3 5 7 8 9 13 15 23 39 48 64

2. To sort the list in descending order.


Syntax
list_name.sort(reverse=True)
This will sort the given list in descending order.

# List of Integers
numbers =[1, 3, 4, 2]
# Sorting list of Integers
numbers.sort(reverse=True)
print(numbers)
# List of Floating point numbers
Decimal number =[2.01, 2.00, 3.67, 3.28, 1.68]
# Sorting list of Floating point numbers
Decimal number.sort(reverse=True)
print(decimal number)
# List of strings
words =["Geeks", "For", "Geeks"]
# Sorting list of strings
words.sort(reverse=True)
print(words)
Output:
[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']

Result:
The above array programs has been entered, executed and the output was obtained.

Staff Signature
4. Python Programming – Matrices
Aim :
To write, enter and execute a python program to add, multiply and transpose
matrices.
1. Python Program to Add Two Matrices

X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[11,12,13],
[14,15,16],
[17,18,19]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
Output:
[12, 14, 16]
[18, 20, 22]
[24, 26, 28]
2. Python Program to Multiply Two Matrices

X = [[1,2,3],

[4,5,6],

[7,8,9]]

Y = [[11,12,13],

[14,15,16],

[17,18,19]]

result = [[0,0,0],

[0,0,0],

[0,0,0]]

# iterate through rows of X

for i in range(len(X)):

for j in range(len(Y[0])):

for kin range(len(Y)):


result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

Output:

[90, 96, 102]


[216, 231, 246]
[342, 366, 390]
3. Python Program to Transpose a Matrix

X = [[3,4],

[6,5],

[7,9]]

result = [[0,0,0],

[0,0,0]]

# iterate through rows

for i in range(len(X)):

for j in range(len(X[0])):

result[j][i] = X[i][j]

for r in result:

print(r)

Output:
[3, 6, 7]
[4, 5, 9]

Result:

The python program to add, multiply and to transpose matrices have been entered,
executed and the output was obtained.

Staff Signature
5. Python programming – solving differential equations

Aim:

To solve differential equations using python programs.

Euler Method for solving differential equation


Given a differential equation dy/dx = f(x, y) with initial condition y(x0) = y0. Find
its approximate solution using Euler method.
Euler Method :
In mathematics and computational science, the Euler method (also called forward
Euler method) is a first-order numerical procedure for solving ordinary differential
equations (ODEs) with a given initial value.
Consider a differential equation dy/dx = f(x, y) with initial condition y(x0)=y0
then successive approximation of this equation can be given by:

y(n+1) = y(n) + h * f(x(n), y(n))


where h = (x(n) – x(0)) / n
h indicates step size. Choosing smaller
values of h leads to more accurate results
and more computation time.

Example :
Consider below differential equation
dy/dx = (x + y + xy)
with initial condition y(0) = 1
and step size h = 0.025.
Find y(0.1).
Solution:
f(x, y) = (x + y + xy)
x0 = 0, y0 = 1, h = 0.025
Now we can calculate y1 using Euler formula
y1 = y0 + h * f(x0, y0)
y1 = 1 + 0.025 *(0 + 1 + 0 * 1)
y1 = 1.025
y(0.025) = 1.025.
Similarly we can calculate y(0.050), y(0.075), ....y(0.1).
y(0.1) = 1.11167
Program:

# Python Code to find approximation of a ordinary differential equation


# using euler method.
# Consider a differential equation
# dy / dx =(x + y + xy)
def func( x, y ):
return (x + y + x * y)
# Function for euler formula
def euler( x0, y, h, x ):
temp = -0
# Iterating till the point at which we
# need approximation
while x0 < x:
temp = y
y = y + h * func(x0, y)
x0 = x0 + h
# Printing approximation
print("Approximate solution at x = ", x, " is ", "%.6f"% y)
# Driver Code
# Initial Values
x0 = 0
y0 = 1
h = 0.025

# Value of x at which we need approximation


x = 0.1
euler(x0, y0, h, x)

Output :

Approximate solution at x = 0.1 is 1.11167

Result:

Euler’s method of solving differential equations using a python program has been
entered, executed and the output was obtained.

Staff Signature
6. Python Programming – Trapezoidal And Simpson Rule
Aim :

To solve numerical integration (Trapezoidal and Simpson’s Rule)using python


programs.

1. Trapezoidal Method
#Trapezoidal Method
# Define function to integrate
def f(x):
return 1/(1 + x**2)
# Implementing trapezoidal method
def trapezoidal(x0,xn,n):
# calculating step size
h = (xn - x0) / n
# Finding sum
integration = f(x0) + f(xn)
for i in range(1,n):
k = x0 + i*h
integration = integration + 2 * f(k)
# Finding final integration value
integration = integration * h/2
return integration
# Input section
lower_limit = float(input("Enter lower limit of integration: "))
upper_limit = float(input("Enter upper limit of integration: "))
sub_interval = int(input("Enter number of sub intervals: "))
# Call trapezoidal() method and get result
result = trapezoidal(lower_limit, upper_limit, sub_interval)
print("Integration result by Trapezoidal method is: %0.6f" % (result) )
Output
Output of above Trapezoidal method Python program is:
Enter lower limit of integration: 0
Enter upper limit of integration: 1
Enter number of sub intervals: 6
Integration result by Trapezoidal method is: 0.784241
2. Simpson's 1/3 Rule

# Simpson's 1/3 Rule


# Define function to integrate
def f(x):
return 1/(1 + x**2)
# Implementing Simpson's 1/3
def simpson13(x0,xn,n):
# calculating step size
h = (xn - x0) / n
# Finding sum
integration = f(x0) + f(xn)
for i in range(1,n):
k = x0 + i*h
if i%2 == 0:
integration = integration + 2 * f(k)
else:
integration = integration + 4 * f(k)
# Finding final integration value
integration = integration * h/3
return integration
# Input section
lower_limit = float(input("Enter lower limit of integration: "))
upper_limit = float(input("Enter upper limit of integration: "))
sub_interval = int(input("Enter number of sub intervals: "))
# Call simpson() method and get result
result = simpson13(lower_limit, upper_limit, sub_interval)
print("Integration result by Simpson's 1/3 method is: %0.6f" % (result) )
Output
Enter lower limit of integration: 0
Enter upper limit of integration: 1
Enter number of sub intervals: 6
Integration result by Simpson's 1/3 method is: 0.785398

Result:
The python programs for trapezoidal and Simpson’s 1/3 rd rule has been
entered,executed and the result was obtained.

Staff Signature:
7. Python Programming – Lagrange’s Interpolation Method

Aim:
To enter and execute Lagrange’s interpolation using python programs.

# Lagrange Interpolation
# Importing NumPy Library
import numpy as np
# Reading number of unknowns
n = int(input('Enter number of data points: '))
# Making numpy array of n & n x n size and initializing
# to zero for storing x and y value along with differences of y
x = np.zeros((n))
y = np.zeros((n))
# Reading data points
print('Enter data for x and y: ')
for i in range(n):
x[i] = float(input( 'x['+str(i)+']='))
y[i] = float(input( 'y['+str(i)+']='))
# Reading interpolation point
xp = float(input('Enter interpolation point: '))
# Set interpolated value initially to zero
yp = 0
# Implementing Lagrange Interpolation
for i in range(n):
p=1
for j in range(n):
if i != j:
p = p * (xp - x[j])/(x[i] - x[j])
yp = yp + p * y[i]
# Displaying output
print('Interpolated value at %.3f is %.3f.' % (xp, yp))
Output: Language Interpolation
Enter number of data points: 5
Enter data for x and y:
x[0]=5
y[0]=150
x[1]=7
y[1]=392
x[2]=11
y[2]=1452
x[3]=13
y[3]=2366
x[4]=17
y[4]=5202
Enter interpolation point: 9
Interpolated value at 9.000 is 810.000.
Result:
Lagrange interpolation using python programs has been entered, executed and
the output was obtained.
Staff Signature
8. Programming – Newton’ Raphson Method Python
Aim:
To enter and execute Newton Raphson method using python programs.

Python Source Code: Newton Raphson Method


# Defining Function
def f(x):
return x**3 - 5*x - 9
# Defining derivative of function
def g(x):
return 3*x**2 - 5
# Implementing Newton Raphson Method
def newtonRaphson(x0,e,N):
print('\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')
step = 1
flag = 1
condition = True
while condition:
if g(x0) == 0.0:
print('Divide by zero error!')
break
x1 = x0 - f(x0)/g(x0)
print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, f(x1)))
x0 = x1
step = step + 1

if step > N:
flag = 0
break
condition = abs(f(x1)) > e
if flag==1:
print('\nRequired root is: %0.8f' % x1)
else:
print('\nNot Convergent.')
# Input Section
x0 = input('Enter Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')
# Converting x0 and e to float
x0 = float(x0)
e = float(e)
# Converting N to integer
N = int(N)
#Note: You can combine above three section like this
# x0 = float(input('Enter Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))
# Starting Newton Raphson Method
newtonRaphson(x0,e,N)

Newton Raphson Python Output


Enter Guess: 2
Tolerable Error: 0.000001
Maximum Step: 10
*** NEWTON RAPHSON METHOD IMPLEMENTATION ***
Iteration-1, x1 = 3.571429 and f(x1) = 18.696793
Iteration-2, x1 = 3.009378 and f(x1) = 3.207103
Iteration-3, x1 = 2.864712 and f(x1) = 0.185915
Iteration-4, x1 = 2.855236 and f(x1) = 0.000771
Iteration-5, x1 = 2.855197 and f(x1) = 0.000000

Required root is: 2.85519654

Result:
The above program has been entered, executed and the output was obtained.

Staff Signature

You might also like