0% found this document useful (0 votes)
50 views55 pages

MP Lap File

The document describes a student's physics practical file containing programs related to numerical methods for solving equations. It includes the aims, theories, algorithms, formulas and Python codes for programs involving the Newton-Raphson, bisection, secant and other root-finding methods applied to physics problems.

Uploaded by

mr.hike.09
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)
50 views55 pages

MP Lap File

The document describes a student's physics practical file containing programs related to numerical methods for solving equations. It includes the aims, theories, algorithms, formulas and Python codes for programs involving the Newton-Raphson, bisection, secant and other root-finding methods applied to physics problems.

Uploaded by

mr.hike.09
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/ 55

ATMA RAM SANATAN DHARMA COLLEGE

University of Delhi

NAME- ADITYA TIWARI


ROLL NO- 23/36099
COURSE- PHYSICS HONS

MATHEMATICAL PHYSICS PRACTICAL FILE


Index
S.No PROG. PAGE NO. SIGN.
1 PROG.-01 1-----3
2 PROG.-02 4-----5
3 PROG.-03 6-----7
4 PROG.-04 8-----10
5 PROG.-05 11----13
6 PROG.-06 13----16
7 PROG.-07 17----19
8 PROG.-08 21----28
9 PROG.-09 29----35
10 PROG.-10 36----45
11 PROG.-11 47----56
12 PROG.-12 57----64
13 PROG.-13 66---71
14 PROG.-14 72---74
PROGRAMME—01
AIM : To approximate nth root of a number up to a given number
of significant digits using Newton–rephson method.
THEORY : The Newton-Raphson method is an iterative technique
for finding the roots of a real-valued function. It starts with an
initial guess and then refines this guess successively to approach
the actual root.
For finding the nth root of a number, you're essentially finding the
root of the function F(x) = Xn – number.
• FUNCTION DEFINITION :
• F(x) is defined as xn - number. The function represents the
equation whose root you want to find.
• DERIVATIVE OF THE FUNCTIONS:
• F’(x) , the derivative of F(x) , is calculated. For f(x) = xn –
number , its derivative F’(x) is n.xn-1.
• ITERATION:
• Start with an initial guess X0.
• Calculate the next approximation x1 using the formula.
• Repeat this process until the change between successive
approximations is within the specified tolerance.
ALGORITHM:
• Defined the function f(x) = xn - number and its derivative f’(x)
= n.xn-1.
• Initialize x with the initial guess.
• Iterate using the Newton-Rephson formula until the difference
between successive approximations is less than the tolerance.
• Return the approximate nth root.
FORMULA USE:
In the Newton-Raphson method implementation provided in the code,
the main formula used for iteration is as follows:
Xnext = x – f(x)/f’(x)
Where :
• X is the current approximation of the root .
• Xnext is the next approximation of the root.
• F(x) is the value of the function at x , defined as xn – number.
• F’(x) is the derivative of the function with respect to x , which is n.xn-1
for F(x) = xn – number.
PYTHON CODE :
OUTPUT :
PROGRAMME—02
AIM : To approximate nth root of a number up to a given number
of significant digits using bisection method.
THEORY : The bisection method is a numerical technique for
finding the roots of a continuous function. It operates by
repeatedly dividing the interval in which the root is believed to be
located into two subintervals and then selecting the subinterval in
which the root must lie for further processing. Here's a
breakdown of the algorithm and the formula used
ALGORITHM :
• Initialize two endpoint of the interval [a ,b] such that f(a) and
f(b) have opposite signs , implying there exists a root between
a and b.
• Calculate the midpoint c of the interval [a,b].
• Check the sign of f(c):
• If f(c) = 0 , them c is the root , and the process terminates.
• If f(a) . f(c) < 0 , then the root lies between a nad c. Update
b = c.
• If f(a) . f(c) > 0 , then the root lies between c and b . Update
a = c.
• Repeat steps 2 and 3 until the interval [a,b] is sufficiently small
, i.e., I b – a I < tolerance.
• Return the midpoint c as the approximate root of the function.
FORMULA USE :
The bisection step involves computing the midpoint c of the interval
[a,b] using the formula:
C = (a+b)/2
PYTHON CODE :

OUTPUT :
PROGRAMME—03
AIM : To approximate nth root of a number up to a given number
of significant digits by using secent method.
THEORY :
The code implements the Secant Method, which is a numerical
technique used to find the root of a function. It's an iterative
method that starts with two initial guesses and refines them
successively to converge towards the root.
ALGORITHM :
1. Start with two initial guesses, X0 and X1.
2. Iterate until convergence, where convergence is typically
determined by a tolerance level.
3. At each iteration, calculate the next approximation Xnext using
the Secant Method formula.
Xnext = Xcurr + (f(Xcurr).((xcurr + xprev) / f(xcurr) – f(xprev)).
4. Update xprev and xcurr for the next iteration.
5. Repeat steps 3-4 until the absolute difference between xcurr
and xprev is less than the specified tolerance.
FORMULA USE : The formula used in the Secant Method for finding
the next approximation Xnext is:

Xnext = Xcurr + (f(Xcurr).((xcurr + xprev) / f(xcurr) – f(xprev)).


Here, f(xcurr) and f(xprev) are the function values at the current and
previous approximations, respectively.
PYTHON CODE :

OUTPUT :
PROGRAMME—04
AIM : Determine the depth up to which a spherical homogeneous object of given
radius and density will sink into a fluid of given density by using bisection method.

THEORY : The bisection method is a numerical technique used to find the root
of a real-valued function. It is based on the intermediate value theorem, which
states that if a continuous function has different signs at two points within an
interval, then it must have at least one root within that interval.

ALGORITHM :
• INPUT PARAMETERS : The algorithm takes the following inputs:
• ‘a’ and ‘b’ : Initial approximations of the root where a < b .
• ‘n’ : Number of iterations.
• ‘object_density ’: Density of the object.
• ‘fluid_density’ : Density of the fluid.
• BRACKETING THE ROOT: Before applying the bisection method, we need
to ensure that the initial approximations a and b bracket the root, i.e., the
function changes sign between a and b. This is checked using the product of
the function values at a and b. If the product is positive, it implies the root is
not bracketed.
• BISECTION ITERATION :
• Calculate the midpoint ‘x’ of the interval ‘[a ,b]’.
• Evaluate the function value ‘depth_of_immersion(x , object_density ,
fluid_density)’.
• Update ‘a’ or ‘b’ based on the sign of the function value at ‘x’.
• If the function value is negative , update ‘a’ to ‘x’ otherwise , update ‘b’
to ‘x’.
• Repeat this process for ‘n’ iterations.
FORMULA USE :
The formula used in the ‘depth_of_immersion’ function is :

Depth = r x (object_density / fluid_density)**1/3


Where :
6. Depth is the depth of immersion of the object.
7. R is the radius of the object.
8. Object_density is the density of the object.
9. Fluid density is the density of the fluid.
PYTHON CODE :
OUTPUT :
PROGRAMME--05
AIM : Determine the depth up to which a spherical homogeneous object
of given radius and density will sink into a fluid of given density by using
secant method.
THEORY :
The Secant Method is a numerical technique used to find the root of a
real-valued function. Unlike the Newton-Raphson method, it doesn't
require the computation of derivatives. Instead, it uses secant lines to
approximate the root of the function within a specified tolerance.
ALGORITHM :
• INPUT PARAMETERS: The algorithm takes the following inputs:
• ‘X0’ AND ‘X1’ : Initial guesses for the root where x0 ! = x1.
• Tolerance : The desired accuracy of the root approximation.
• Max_iterations : Maximum number of iterations allowed.
• SECANT ITERATION:
• Calculate the function values ‘f(x0)’ and ‘f(x1)’.
• Compute the next approximation ‘x_n’ using the secant formula.
• Update the values of ‘x0’ and ‘x1’.
• Repeat thos process until either the absolute difference between
consecutive approximation is less than the specified tolerance or the
maximum number of iteration is reached.
• OUTPUT : If the root is found within the specified tolerance and maximum
iterations, the algorithm outputs the final approximated depth of the
spherical object. Otherwise, it indicates that the method did not converge
within the given constraints.

FORMULA USE:
The secant formula used in the algorithm to compute the next
approximation ‘x_n’ is:
Xn = X1 - f(X1) x ( X1 – X0)/f(X1) –f(X0)
Where :
10. Xn is the next approximation.
11. X0 and X1 are the current approximations.

12. F(X0) and F(X1) are the function values at X0 and X1 , respectively.

PYTHON CODE :

OUTPUT :
PROGRAMME—06
AIM : Solve transeendental equation like α = tan(α) using secant
method.
THEORY: The code implements the Secant method which is an
iterative root-finding algorithm used to find the roots of a given
equation. It's an improvement over the simpler method of the
Newton-Raphson algorithm, as it doesn't require the calculation
of the derivative of the function.
ALGORITHM :
• INITIALIZATION:
• The algorithm start with two initial guesses , X0 and X1 ,
which should ideally bracket the root.
• ITERATION :
• It iteratively updates the value of X0 and X1 using the
formula derived from the secant line between the points
(X0 , F(X0)) and (X1 , f(X1)).
• The formula used for updating x1 is:
Xnext = X1 – f(X1) x (x1 –x0)/f(x1) – f(x0)
13. TERMINATION :
14. The iteration stop when either the absolute
difference between consecutive iterations becomes
smaller than a predefined tolerance or when a maximum
number of iterations is reached.
15. OUTPUT:
16. The algorithm return the approximate root if found
within the specified tolerance and maximum iterations.
FORMULA USE :
Xnext = X1 – f(X1) x (x1 –x0)/f(x1) – f(x0)
PYTHON CODE :

OUTPUT :
PROGRAMME—07
AIM : Solve transeendental equation like α = tan(α) by using newton
raphson method
THEORY : The Newton-Raphson method is an iterative numerical
technique used to find the root of a real-valued function. It is based on
the concept of using successive approximations to iteratively converge
towards the root of the function. The method is particularly effective for
functions that are differentiable and have a continuous first derivative.
ALGORITHM :
• INPUT PARAMETER : The algorithm takes the following inputs:
• Initial_guess : An initial approximation of the root .
• Tolerance : The desired accuracy of the root approximation.
• Max_iterations : Maximum number of iterations allowed.
• NEWTON-REPHSON ITERATION :
• Initialze ‘x’ with the initial guess .
• For each iteration:
• Calculate the function value ‘f(x)’ using the given equation.
• Calculate the derivative ‘f’(x)’ using the provided derivative
function.
• Update ‘x’ using the Newton-rephson formula.
• Check if the absolute difference between consecutive
approximations is less than the specified tolerance.if so ,
return the current approximation as the root.
• If the root is not found within within the maximum number of
iterations , return ‘None’.
OUTPUT : If the root is found within the specified tolerance and maximum
iterations, the algorithm outputs the approximated root of the equation.
Otherwise, it indicates that the method did not converge within the given
constraints.
FORMULA USED :
The Newton-Rephson formula used in the algorithm to compute the
next approximation Xn+1 is :
Xn+1 = Xn – (f(Xn)/f’(Xn))
Where :
• Xn+1 is the next approximation.
• Xn is the current approximation.
• F(Xn) is the function value at Xn.
• F’(Xn) is the derivative of the function at Xn .
PYTHON CODE :
OUTPUT :
UNIT—02
LEAST SQUARE FITTING
PROGRAMME—08
AIM: Make a function for least square fitting, use it for fitting
given data (x, y) and estimate the
parameters a, b as well as uncertainties in the parameters for the
following cases.
i. Linear (𝑦=ax+b)

THEORY: The least squares method is a form of mathematical


regression analysis used to determine the line of best fit for a set
of data, providing a visual demonstration of the relationship
between the data points. Each point of data represents the
relationship between a known independent variable and an
unknown dependent variable.

The least-square method states that the curve that best fits a
given set of observations, is said to be a curve having a minimum
sum of the squared residuals (or deviations or errors) from the
given data points. Let us assume that the given points of data are
(x1, y1), (x2, y2), (x3, y3), …, (xn, yn) in which all x’s are independent
variables, while all y’s are dependent ones. Also, suppose that f(x)
is the fitting curve and d represents error or deviation from each
given point.
Now, we can write:
d1 = y1 − f(x1)
d2 = y2 − f(x2)
d3 = y3 − f(x3)
…..
dn = yn – f(xn)
The least-squares explain that the curve that best fits is
represented by the property that the sum of squares of all the
deviations from given values must be minimum, i.e:

Sum = Minimum Quantity


Suppose when we have to determine the equation of line of best
fit for the given data, then we first use the following formula.
The equation of least square line is given by Y = a + bX
Normal equation for ‘a’:
∑Y = na + b∑X
Normal equation for ‘b’:
∑XY = a∑X + b∑X2
Solving these two normal equations we can get the required trend
line equation.
Thus, we can get the line of best fit with formula y = ax + b
ALGORITHM:
Step 1: Start
Step 2: Import the required libraries:
- `matplotlib.pyplot`
- `linregress` from `scipy.stats`.
Step 3: Define a function `fit(n)` that takes an integer `n` as input.
 Initialize empty lists `x` and `y`.
 Prompt the user to input values for `x` and `y` in a loop `n`
times.
Step 4: Initialize variables:
- `xy`, `sumx`, `sumy`, and `sqx` to 0.
Step 5: Calculate the sums and squared sums of `x` and `y` using a
loop.
 Use a loop to iterate through the values of `x` and `y`:
 Calculate `xy` as the sum of products of corresponding `x`
and `y` values.
 Calculate `sumx` as the sum of all `x` values.
 Calculate `sumy` as the sum of all `y` values.
 Calculate `sqx` as the sum of squares of all `x` values.
Step 6: Calculate the slope `a1` using the formula: `(n*xy -
sumx*sumy) / (n*sqx - sumx**2)`.
Step 7: Calculate the y-intercept `a0` using the formula: `sumy/n -
a1*sumx/n`.
Step 8: Initialize variables `x1` and `x2` to 0.
Step 9: Iterate through the `x` values to find `x1` and `x2`.
 Use a loop to iterate through the values of `x`:
 Check if `x[i] < x[i-1]`.
o If true, update `x1` to `x[i]`.
o If false, update `x2` to `x[i]`.
Step 10: Print the calculated slope `a1` and y-intercept `a0`.
Step 11: Use `linregress` function to calculate slope and y-
intercept using built-in method.
Step 12: Print the slope and y-intercept calculated using the built-
in function.
Step 13: Plot the scatter plot of `x` and `y`.
Step 14: Calculate `y1` and `y2` for plotting the line.
Step 15: Plot the line of best fit using `x1`, `x2`, `y1`, and `y2`.
Step 16: Show the plot.
Step 17: End.
CODE:
oo

INPUT:-
GRAPH:_

RESULT:
The Python program fits the given data (x, y) and estimate the
parameters a, b as well as uncertainties in the parameters for
linear (𝑦= 𝑎x+b).
PROGRAMME—09
AIM: Make a function for least square fitting, use it for fitting
given data (x, y) and estimate the
parameters a, b as well as uncertainties in the parameters for the
following cases.
ii. Power law (𝑦 = 𝑎xb)

THEORY: The least squares method is a form of mathematical


regression analysis used to determine the line of best fit for a set
of data, providing a visual demonstration of the relationship
between the data points. Each point of data represents the
relationship between a known independent variable and an
unknown dependent variable.

The least-square method states that the curve that best fits a
given set of observations, is said to be a curve having a minimum
sum of the squared residuals (or deviations or errors) from the
given data points. Let us assume that the given points of data are
(x1, y1), (x2, y2), (x3, y3), …, (xn, yn) in which all x’s are independent
variables, while all y’s are dependent ones. Also, suppose that f(x)
is the fitting curve and d represents error or deviation from each
given point.
Now, we can write:
d1 = y1 − f(x1)
d2 = y2 − f(x2)
d3 = y3 − f(x3)
…..
dn = yn – f(xn)
The least-squares explain that the curve that best fits is
represented by the property that the sum of squares of all the
deviations from given values must be minimum, i.e:

Sum = Minimum Quantity


Suppose when we have to determine the equation of line of best
fit for the given data, then we first use the following formula.
The equation of least square line is given by Y = a + bX
Normal equation for ‘a’:
∑Y = na + b∑X
Normal equation for ‘b’:
∑XY = a∑X + b∑X2
Solving these two normal equations we can get the required trend
line equation.
Given a function of the form
(1)
Least Squares Fitting gives the Coefficients as
b = nΣ(log x log y)- Σ(log x) Σ(log y)
(2)
nΣ[(log x)^2] – (Σlog x)^2
(3)
a = Σ(log y)- bΣ(log x)
n

where and

A=10^a
ALGORITHM:
Step 1: Start
Step 2: Import necessary modules:
 numpy as np
 array as arr
 matplotlib.pyplot as plt

Step 3: Define the function 'fit(x, y)' for fitting the data:
 Initialize empty lists X and Y of size n.
 Convert each element of x and y to base-10 logarithm and
store in X and Y respectively.
 Initialize variables xy, sumx, sumy, sqx to 0.
 Calculate the sums and products required for the formula.
 Calculate slope 'a1' and y-intercept 'a0' using the formula.
 Calculate 'a' (y-intercept) and 'b' (slope).
 Use numpy's polyfit to find the slope and y-intercept.
 Get minimum and maximum values of x.
 Create arrays xx and yy for plotting.
 Generate 1000 values between the minimum and maximum
of x and calculate y values for plotting.
 Plot the data points and the best fit curve using matplotlib.

Step 4: Initialize empty arrays x and y.


Step 5: Input the number of elements 'n'.
Step 6: Print "Input the data values of x and y".
Step 7: Iterate 'n' times:
 Read input values for x and y, convert to float, and append
to arrays x and y respectively.
Step 8: Call the 'fit' function with inputs x and y.
Step 9: Stop
CODE:
INPUT:_
GRAPH:-
PROGRAMME—10
AIM: Make a function for least square fitting, use it for fitting
given data (x, y) and estimate the
parameters a, b as well as uncertainties in the parameters for the
following cases.
iii. Exponential (𝑦 = 𝑎ebx)

THEORY: The least squares method is a form of mathematical


regression analysis used to determine the line of best fit for a set
of data, providing a visual demonstration of the relationship
between the data points. Each point of data represents the
relationship between a known independent variable and an
unknown dependent variable.

The least-square method states that the curve that best fits a
given set of observations, is said to be a curve having a minimum
sum of the squared residuals (or deviations or errors) from the
given data points. Let us assume that the given points of data are
(x1, y1), (x2, y2), (x3, y3), …, (xn, yn) in which all x’s are independent
variables, while all y’s are dependent ones. Also, suppose that f(x)
is the fitting curve and d represents error or deviation from each
given point.
Now, we can write:
d1 = y1 − f(x1)
d2 = y2 − f(x2)
d3 = y3 − f(x3)
…..
dn = yn – f(xn)
The least-squares explain that the curve that best fits is
represented by the property that the sum of squares of all the
deviations from given values must be minimum, i.e:

Sum = Minimum Quantity


Suppose when we have to determine the equation of line of best
fit for the given data, then we first use the following formula.
The equation of least square line is given by Y = a + b X
Normal equation for ‘a’:
∑Y = n a + b ∑X
Normal equation for ‘b’:
∑XY = a ∑X + b∑X2
Solving these two normal equations we can get the required trend
line equation.
To fit a functional form
(1)

take the Logarithm of both sides


(2)

The best-fit values are then

(3)

(4)

where and .

This fit gives greater weights to small values so, in order to


weight the points equally, it is often better to minimize the
function

(5)
Applying Least Squares Fitting gives
(6)

(7)

(8)

Solving for and ,

(9)
ALGORITHM:

Step 1: Start

Step 2: Import necessary modules:


- numpy as np
- array as arr
- matplotlib.pyplot as plt

Step 3: Define the function 'fit(x, y)' for fitting the data:
 Initialize an empty list Y of size n.
 Take the natural logarithm of each element of y and store it
in Y.
 Initialize variables xy, sumx, sumy, sqx to 0.
 Calculate the sums and products required for the formula.
 Calculate slope 'a1' and y-intercept 'a0' using the formula.
 Calculate 'a' (y-intercept) and 'b' (slope).
 Use numpy's polyfit to find the slope and y-intercept.
 Get minimum and maximum values of x.
 Create arrays xx and yy for plotting.
 Generate 1000 values between the minimum and maximum
of x and calculate y values for plotting.
 Plot the data points and the best fit curve using matplotlib.
Step 4: Initialize empty arrays x and y.
Step 5: Input the number of elements 'n'.
Step 6: Print "Input the data values of x and y".
Step 7: Iterate 'n' times:
 Read input values for x and y, convert to float, and append
to arrays x and y respectively.

Step 8: Call the 'fit' function with inputs x and y.

Step 9: Stop

CODE:
INPUTS:-

GRAPH:-

RESULT:
The Python program fits the given data (x, y) and estimate the
parameters a, b as well as uncertainties in the parameters for
exponential law (𝑦 = 𝑎ebx).
UNIT 3
Numerical solution of ODE
PROGRAMME—11
AIM– Solve given first order differential equation numerically
using Euler, RK2, RK4 methods and apply to the following physics
problem:
i) Radioactive decay
ii)Newton’s law of cooling

THEORY—
Euler Method
In Euler’s method, you can approximate the curve of the solution
by the tangent in each interval (that is, by a sequence of short line
segments), at steps of h.In general, if you use small step sizes, the
accuracy of approximation increases.

Formula for Euler’s Method–

Modified Euler Method–


Instead of approximating f (x, y) by f (x0 , y0 ) in euler method, we
now approximate the integral by means of trapezoidal rule to
obtain the following formula–

Runge Kutta Method —--


The Runge-Kutta(R-K) technique is an efficient and commonly
used approach for solving initial-value problems of differential
equations. It's used to generate high-order accurate numerical
methods without the necessity for high-order derivatives of
functions.

Second order Runge Kutta (RK2)

Fourth Order Runge Kutta(RK4)

The R-K4 method is the most frequently used R-K method for
solving differential equations.
The Runge-Kutta method estimates y for a given position x.

Formula–

i) Radioactive decay by Euler method-

INPUT CODE-
Output–
ii) Radioactive decay by RK2
INPUT CODE–

OUTPUT–
iii) Radioactive decay by RK4
INPUT CODE-

OUTPUT –
Newton’s law of cooling
i) Newton’s law of cooling by Euler method-
INPUT CODE-
OUTPUT–

iv) Newton’s law of cooling by RK2-


INPUT CODE–
OUTPUT–

vi) Newton’s law of cooling by RK4-


INPUT CODE–
OUTPUT–

You might also like