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

Computational Sem 5

Computational physics record

Uploaded by

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

Computational Sem 5

Computational physics record

Uploaded by

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

Contents

1 Frequency table for a given set of number. 2

2 Program to creating sets 4

3 The correlation coefficient between two sets of data. 7

4 To construct a least square fit of data to a straight line. 10

5 Euler’s algorithm for solving the Volterra’s predator-prey equations. 12

6 The trajectory of a random walker taking N random steps in two dimensions. 15

7 Van der Pol equation 18

1
Experiment 1
Frequency table for a given set of
number.
Date - 01-07-2024
Aim
To create a frequency table for a given set of number, with table sorted by numbers.

Principle
A frequency table is a statistical tool used to organize a set of data by showing the frequency (or count) of each
distinct value in the data set. In computational physics and data analysis, frequency tables help understand the
distribution of values, highlighting patterns or anomalies in datasets. Python, being a powerful programming
language for data manipulation, can be used to automate the generation of frequency tables, especially when
the dataset is large.
The algorithm for generating a frequency table from a set of numbers includes the following steps:
Data Input: The data is read from a text file where each number is stored. Data Cleaning: Ensure that the
data is in numerical form and remove any non-numerical values or anomalies if necessary.
Counting Frequency: Use an appropriate data structure (like a dictionary) to count the occurrences of each
unique number.
Sorting the Numbers: Sort the numbers in ascending order for easy interpretation and analysis.
Displaying the Frequency Table: Present the sorted numbers alongside their corresponding frequencies.
This process is efficient for handling datasets of varying sizes, and the results provide insights into the distribution
of values in the dataset.

Code
from collections import Counter
import pandas as pd
F=Counter(Data)
Data = [3,4,3,2,3,4,3,2,1,1,2,5,5,6,6,7,0,9,8,7,6,7]
Ft=pd.DataFrame(list(F.items()),columns=[’value’,’Frequency’])
print(Ft)

2
Frequency table for a given set of number. 3

Result
Experiment 2
Program to creating sets
Date - 01-07-2024
Aim
To write a program to creating sets, checking whether a number is in the set, making cartesian products and
other set operations.

Principle
In mathematics, a set is a well-defined collection of distinct objects or elements. Python provides the set
data type, which supports various operations common in set theory, including membership testing, union,
intersection, difference, and Cartesian products. These operations are fundamental in many fields such as
physics, computer science, and data analysis where the manipulation of collections of unique elements is required.
The key principles involved are:

1. Creating Sets: A set is an unordered collection of unique elements. In Python, sets can be created using
curly braces {} or the set() function. Any duplicates in the data are automatically removed.
2. Checking Membership: To determine whether a specific element belongs to a set, Python uses the in
keyword. This operation is highly efficient, as set membership tests are performed in constant time on
average.
3. Set Operations: Sets support various operations that are aligned with mathematical set theory:
• Union: Combines all elements from two sets. This operation is performed using the | operator or
the union() method.
• Intersection: Returns only the common elements of two sets, performed using the & operator or
intersection() method.
• Difference: The elements present in one set but not in another, done using the - operator or
difference() method.
• Symmetric Difference: The elements present in either of the sets, but not in both, performed
using the ^ operator or symmetric difference() method.
4. Cartesian Product: The Cartesian product of two sets is the set of all ordered pairs, where the first
element of each pair comes from the first set, and the second element comes from the second set. In
Python, the Cartesian product is computed using the itertools.product() function, which returns an
iterable of tuples representing all possible pairs of elements.

This program demonstrates the basic set operations in Python, such as membership checking, union, intersection,
difference, and the Cartesian product. These operations are crucial for efficiently handling collections of unique
data in both theoretical and practical applications.

4
Program to creating sets 5

Code
from sympy import FiniteSet
s=FiniteSet(1,2,3)
t=FiniteSet(3,4,5)
u=FiniteSet(5,6,7)
a=4 in s
b=len(s)
c=s*t
for elem in c:
print(elem)
d=s.union(t).union(u)
e=s.intersect(t).intersect(u)
f=s**3
for elem in f:
print(elem)
print(s,a,b,d,e,)

Result
Program to creating sets 6
Experiment 3
The correlation coefficient between two
sets of data.
Date - 08-07-2024
Aim
To calculate the correlation coefficient between two sets of data and to construct a scatter plot showing the
relationship.

Principle
The correlation coefficient is a statistical measure that quantifies the strength and direction of the relationship
between two variables. In most cases, the Pearson correlation coefficient is used, which measures the linear
relationship between two sets of data. The correlation coefficient value (denoted as r) ranges between -1 and 1:
• r = 1: Perfect positive correlation (as one variable increases, the other increases proportionally).
• r = −1: Perfect negative correlation (as one variable increases, the other decreases proportionally).
• r = 0: No correlation (no linear relationship between the variables).

The formula for the Pearson correlation coefficient r is:


P P P
n( xy) − ( x)( y)
r= p P P P P
[n x2 − ( x)2 ][n y 2 − ( y)2 ]
Where:
• n is the number of data points,

• x and y are the two data sets,



P
xy is the sum of the product of paired values,

P P
x and y are the sums of the data sets,

P 2 P 2
x and y are the sums of the squares of the data sets.

Steps Involved:
1. Data Input: The two sets of data X and Y are read from a text file. Each line of the file contains paired
values of x and y.
2. Calculating the Correlation Coefficient: The Pearson correlation coefficient is calculated using the
formula, or alternatively, using Python’s numpy or scipy libraries for convenience. These libraries provide
built-in functions to efficiently compute the correlation.

7
The correlation coefficient between two sets of data. 8

3. Constructing a Scatter Plot: A scatter plot is a graphical representation of the two data sets where
each point represents a pair of (x, y) values. The plot helps visualize the relationship between the two
variables, showing any positive, negative, or no correlation. Python’s matplotlib library is commonly
used for plotting.

The correlation coefficient helps quantify the linear relationship between two sets of data, while the scatter
plot provides a visual representation of this relationship. Both tools are crucial in statistical analysis, physics,
and data science for understanding how variables are related.

Code
import numpy as np
import matplotlib.pyplot as plt

a= np.array([300, 350, 400, 450, 500])


b= np.array([100,200,150,350,400])
correlation_matrix = np.corrcoef(a, b)
correlation_coefficient = correlation_matrix[0, 1]

print(f"Pearson correlation coefficient: {correlation_coefficient}")

plt.figure(figsize=(10, 6))
plt.plot(a,b,’o-’)
plt.xlabel(’a’)
plt.ylabel(’b’)
plt.title(’a vs. b’)

plt.grid(True)
plt.show()

Result
Pearson correlation coefficient: 0.9162708326722891
The correlation coefficient between two sets of data. 9
Experiment 4
To construct a least square fit of data
to a straight line.
Date - 05-08-2024
Aim
To construct a least square fit of data to a straight line.

Principle
The least squares fitting method is one of the most commonly used techniques to find the best-fitting line for a
set of data points. It minimizes the sum of the squares of the vertical deviations between the observed values
and the values predicted by the line. The goal is to find the line y = mx + c, where m is the slope and c is
the y-intercept, that best represents the relationship between the independent variable x and the dependent
variable y.
In least squares fitting, the best-fit line is determined by minimizing the residual sum of squares (RSS),
defined as:
n
X
RSS = (yi − (mxi + c))2
i=1

Where:
• (xi , yi ) are the given data points,
• m is the slope of the best-fitting line,
• c is the intercept of the best-fitting line,
• n is the number of data points.
The formulas to calculate the slope m and intercept c of the best-fitting line are:
P P P
n( xi yi ) − ( xi )( yi )
m=
n( x2i ) − ( xi )2
P P

( yi )( x2i ) − ( xi )( xi yi )
P P P P
c=
n( x2i ) − ( xi )2
P P

Steps Involved:
1. Data Input: The x and y values are the observed data points.
2. Calculating Slope and Intercept: Use the least squares method to compute the slope m and the
intercept c based on the given data.
3. Plotting the Data and Line: A scatter plot of the data points is constructed, and the least squares
line is plotted alongside the data.

10
To construct a least square fit of data to a straight line. 11

The least squares method is particularly useful in physics, engineering, and data science when one wishes
to model a linear relationship between two variables. The approach assumes that the errors in the dependent
variable (y) are normally distributed and that the relationship between the independent and dependent variables
is approximately linear.
The least squares method provides an effective way to approximate a linear relationship between two variables
by minimizing the discrepancies between observed data points and the predicted values. This technique helps
find the best-fitting straight line for data, which can be used for further analysis and predictions.

Code
import numpy as np
import matplotlib.pyplot as plt
x=np.array([1,2,3,4,5])
y=np.array([4,5,8,10,12])
coef=np.polyfit(x,y,1)
slope,intercept=coef
y_fit=slope*x+intercept
print(f"slope.{slope}")
print(f"intercept.{intercept}")
plt.scatter(x,y,label=’Data’)
plt.plot(x,y_fit)
plt.show()

Result
slope.2.0999999999999996
intercept.1.5000000000000018
Experiment 5
Euler’s algorithm for solving the
Volterra’s predator-prey equations.
Date - 05-08-2024
Aim
Apply Euler’s algorithm for solving the Volterra’s predator-prey equations with a suitable initial conditions and
visualization of the phase diagram.

Principle
The Volterra’s predator-prey equations, also known as the Lotka-Volterra equations, describe the dynamics of
biological systems in which two species interact, one as a predator and the other as prey. These equations are
a pair of first-order, nonlinear differential equations and are given by:
dx
= αx − βxy
dt
dy
= δxy − γy
dt
Where:
• x(t) represents the prey population at time t,
• y(t) represents the predator population at time t,
• α is the natural growth rate of the prey in the absence of predators,

• β is the rate at which predators destroy prey,


• γ is the natural death rate of predators in the absence of prey,
• δ is the rate at which predators increase by consuming prey.

Numerical Solution Using Euler’s Algorithm:


Euler’s method is a simple, first-order numerical method for solving ordinary differential equations (ODEs).
It uses the formula:

xn+1 = xn + h · f (tn , xn )
Where:
• h is the step size,

• xn is the value at the current step,


• f (tn , xn ) is the derivative of x with respect to time.

12
Euler’s algorithm for solving the Volterra’s predator-prey equations. 13

For the predator-prey system, we have two coupled equations, and Euler’s method is applied iteratively to
both the prey and predator populations.
Steps Involved:
1. Initial Conditions: Define initial values for the prey and predator populations x(0) and y(0), and choose
the parameters α, β, γ, and δ. Also, select a time step h and the total simulation time.
2. Euler’s Method Application: Using the differential equations, update the populations of prey and
predators at each time step using Euler’s method.
3. Phase Diagram Visualization: The phase diagram is a plot of the prey population x(t) versus the
predator population y(t). This provides a visual representation of the interaction between the two popu-
lations over time. By analyzing the trajectory in the phase space, one can understand the cyclical nature
of the predator-prey system.
Euler’s algorithm provides an approximate solution to the Volterra’s predator-prey equations by discretizing
the time variable. The phase diagram helps visualize the dynamic interaction between the predator and prey
populations, often showing cyclic behavior in the absence of external forces. This model is widely used in
ecology and other fields to study population dynamics.

Code
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def volterra (y,t,a,b,d,g):
prey,predator=y
dydt = [prey*a-b*prey*predator,d*prey*predator-g*predator]
return dydt
a=0.1
b=0.02
d=0.01
g=0.1
prey0= 40
predator0=9
y0=[prey0,predator0]
t=np.linspace(0,200,500)
solution=odeint(volterra,y0,t,args=(a,b,d,g))
prey,predator= solution.T
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.plot(t,prey,label=’prey’)
plt.plot(t,predator,label=’predator’)
plt.xlabel=(’Time’)
plt.ylabel=(’Population’)
plt.legend()
plt.title(’prey predator population’)
plt.subplot(1,2,2)
plt.plot(prey,predator)
plt.xlabel=(’prey’)
plt.ylabel=(’predator’)
plt.title(’Phase plane’)
plt.tight_layout()
plt.show()
Euler’s algorithm for solving the Volterra’s predator-prey equations. 14

Result
Experiment 6
The trajectory of a random walker
taking N random steps in two
dimensions.
Date - 12-08-2024
Aim
To display the trajectory of a random walker taking N random steps in two dimensions, and to study the
variation of square of distance travelled with number of steps N, by taking average of large number of walks

Principle
A random walk is a stochastic process that describes a path consisting of a succession of random steps. In two
dimensions, at each step, the walker moves in one of the four cardinal directions (up, down, left, or right) with
equal probability. The position of the random walker after N steps can be studied to understand the behavior
of diffusion-like processes.
For a random walk in two dimensions, the displacement from the origin after N steps is given by:
q
rN = x2N + yN 2

Where:
• xN and yN are the coordinates of the random walker after N steps.
2
For large N , the mean square displacement ⟨rN ⟩ (the average square of the distance from the origin) is
proportional to N :
2
⟨rN ⟩∝N
This relationship signifies that the random walk is a diffusive process, with the mean square displacement
growing linearly with the number of steps.
Steps Involved:
1. Simulating the Random Walk: The random walker starts at the origin, and for each of the N steps,
it randomly selects one of the four possible directions (up, down, left, or right) and moves by one unit in
that direction. The new position is updated after each step.
2. Trajectory Display: The trajectory of the random walker can be visualized by plotting the position of
the walker at each step. This provides insight into the path taken by the walker over time.
p
3. Distance Calculation: After each step, the displacement from the origin is calculated as rN = x2N + yN
2 ,

where xN and yN are the walker’s coordinates after N steps.


4. Averaging Over Multiple Walks: To study the variation of the square of the distance traveled with
the number of steps N , the random walk is repeated many times (say M walks). The average of the
2
square of the distance from the origin ⟨rN ⟩ is calculated for each step count N .

15
The trajectory of a random walker taking N random steps in two dimensions. 16

2
5. Study of Variation: A plot of ⟨rN ⟩ versus N is generated to observe how the mean square distance
grows with the number of steps, typically showing a linear relationship.
A random walk in two dimensions exhibits diffusive behavior, where the square of the distance from the
origin grows linearly with the number of steps. By averaging the results of a large number of random walks,
the mean square displacement can be studied, providing insights into diffusion processes in physics and other
fields.

Code
import random
import numpy as np
import matplotlib.pyplot as plt
def variance(x,y):
r= np.array(x)**2+np.array(y)**2
plt.plot(np.arange(len(r)),r)
n=1000
x=[0]
y=[0]
directions =[0,1,2,3]
plt.figure(figsize=(10,10))
for i in range (n-1):
dir=random.choice(directions)
if dir==0:
x.append(x[-1]+1)
y.append(y[-1])
elif dir == 1:
x.append(x[-1])
y.append(y[-1]+1)
elif dir==2:
x.append(x[-1]-1)
y.append(y[-1])
else:
x.append(x[-1])
y.append(y[-1]-1)
plt.subplot(2,1,1)
plt.plot(x,y)
plt.subplot(2,1,2)
variance (x,y)
plt.title(’Random walk in 2D’)
plt.show()
The trajectory of a random walker taking N random steps in two dimensions. 17

Result
Experiment 7
Van der Pol equation
Date - 19-08-2024
Aim
Solve van der Pol equation using Euler’s algorithm and study the phase trajectories under chaotic conditions.

Principle
The Van der Pol equation is a second-order nonlinear differential equation used to describe oscillatory systems,
particularly those that exhibit self-sustained oscillations. The equation is given by:

d2 x dx
− µ(1 − x2 ) +x=0
dt2 dt
Where:

• x(t) is the dependent variable (displacement),


• µ is a parameter that controls the nonlinearity and the damping of the system.
For small values of µ, the system shows periodic behavior, but for large values of µ, the system exhibits
complex, potentially chaotic dynamics.
Rewriting the second-order equation as a system of first-order equations:
dx
=y
dt
dy
= µ(1 − x2 )y − x
dt
Euler’s Method:
Euler’s method is a numerical technique for solving ordinary differential equations by approximating the
solution iteratively. For a system of first-order equations, the method is applied as:

xn+1 = xn + h · fx (xn , yn )
yn+1 = yn + h · fy (xn , yn )
Where:
• h is the time step size,
• fx (xn , yn ) = yn ,

• fy (xn , yn ) = µ(1 − x2n )yn − xn .


Steps Involved:
1. Initial Conditions: Start with initial conditions x(0) and y(0), choose a step size h, and set a value for
µ that introduces chaotic behavior (large values of µ, typically greater than 1).

18
Van der Pol equation 19

2. Numerical Solution Using Euler’s Algorithm: Apply Euler’s method to solve the system of equations
iteratively. Update the values of x and y at each time step and track the evolution of the system over
time.

3. Phase Trajectory: Plot the phase trajectory by graphing y(t) (velocity) versus x(t) (displacement).
The phase trajectory visualizes the system’s state as it evolves in time.
4. Study of Chaotic Behavior: For large values of µ, the system exhibits chaotic behavior. The phase
trajectory under these conditions no longer follows a regular orbit but shows a sensitive dependence on
initial conditions, characteristic of chaos.

The Van der Pol oscillator exhibits a range of behaviors depending on the value of µ, transitioning from
periodic oscillations for small values of µ to chaotic dynamics for larger values. Euler’s method provides an
approximate solution to the equation, and the phase trajectory is a valuable tool to visualize the system’s
dynamic behavior, particularly under chaotic conditions. .

Code
import numpy as np
import matplotlib.pyplot as plt

mu = 0.5
h = 0.001
t_final = 100

x0 = 1.0
v0 = 0.0

t = np.arange(0, t_final, h)

x = np.zeros(len(t))
v = np.zeros(len(t))

x[0] = x0
v[0] = v0

for i in range(1, len(t)):


x[i] = x[i-1] + h * v[i-1]
v[i] = v[i-1] + h * (mu * (1 - x[i-1]**2) * v[i-1] - x[i-1])
plt.figure(figsize=(10, 6))
plt.plot(x, v, label=f’$\mu$={mu}’, color=’b’)
plt.title(’Phase Trajectory of the Van der Pol Oscillator’)
plt.xlabel(’x’)
plt.ylabel(’v’)
plt.grid(True)
plt.legend()
plt.show()
Van der Pol equation 20

Result

You might also like