Statistical Mechanics Python Code
Statistical Mechanics Python Code
Jeet Bhattacharjee
March 4, 2024
1
Contents
1 Introduction 1
3 Statistical Ensembles 11
3.1 Statistical Coin Tossing . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 Statistical Ball Choosing . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.7 Statistical Dice Throw . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.8 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.9 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
4 Probability Distributions 17
4.1 Binomial Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.4 Different Variates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.5 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2
5 Transformation Between Distributions 23
5.1 Different Transformations . . . . . . . . . . . . . . . . . . . . . . . . 23
5.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7 Random Walk 36
7.1 Problem 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7.4 Problem 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.5 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3
1 Introduction
This is just a compilation of the Python programs done during Semester - V of aca-
demic year 2023-24. The Python files have been done using Google Colab, Jupyter
Notebook. And this entire notebook is Scripted using LATEX in www.overleaf.com
1
2 Plotting of Random Numbers
2.1 Problem 1
Generate 1000 uniform random numbers between [0,1] using the python module
random or numpy.random . Plot these random numbers with histograms with even
bin size 0.2.
import numpy as np
import matplotlib . pyplot as plt
x = np . random . random (1000)
plt . hist (x ,5 , color = ’r ’ , edgecolor = ’k ’)
plt . title ( " Uniform Random Number Generation " )
plt . show ()
2.3 Output
2
2.4 Problem 2
Repeat the above task with uniform random integers between [1,100].
import numpy as np
import matplotlib . pyplot as plt
2.6 Output
3
2.7 Problem 3
Generate 1000 uniform random integers. Get the mean and median of these num-
bers.
import numpy as np
import matplotlib . pyplot as plt
return men
if n % 2 == 0 :
med = ( dist [ int ( n /2) ] + dist [ int ( n /2) + 1 ] ) * 0.5
if n % 2 == 1 :
med = dist [ int ( n /2) ]
return med
2.9 Output
The mean of the sample is : 49.01617757255107
The median of the sample is : 22.328672027386187
4
2.10 Problem 4
Generate N uniform random numbers X = x0 , x1 , ...., xN −1 between [a, b]. Write a
program to obtain the distribution of X with bins = min(X), min(X) + dx, min(x)
+ 2x, ...., max(X). Choose N = 5000, a = −1.3, b = 1.3anddx = 0.05
import numpy as np
import matplotlib . pyplot as plt
# N_bins = int (( b - a ) / dx )
x = np . random . uniform (a ,b , N )
N_bins = np . arange ( min ( x ) , max ( x ) , dx )
2.12 Output
5
2.13 Problem 5
The nth central moment of variables X = x0 , x1 , ...., xN −1 is given by
PN −1
n |xi − ⟨x⟩n |
σX = ⟨ i=0 ⟩
N
where 〈Z〉 is defined as the average of Z variables. Get an array of 1000 uniform
random numbers between [0,1]. Get the arrays of σx , σ2 . Plot each array with
histogram with proper bin size.
#N - th moment
import numpy as np
import matplotlib . pyplot as plt
return sig_x_n
6
2.15 Output
7
2.16 Problem 6
Write a function to obtain the mean and variance of a given set of numbers.
return men
return variance
2.18 Output
The mean of the sample is : 51.13327955961014
The Variance of the sample is : 845.8847643467384
8
2.19 Problem 7
Create N number of uniform random numbers X = x0 , ..., xN −1 between [−π, π]
2. Plot histograms of the mean of n numbers (<Xn >) taken randomly from X.
<Xn >−µ
3. Plot histograms of σ2
for n numbers taken randomly from X.
import numpy as np
import matplotlib . pyplot as plt
Mean = np . mean ( x )
Variance = np . std ( x ) **2
Median = np . median ( x )
n = 200
mean = []
Given = []
9
2.21 Output
Mean is : -0.02065831694651789
Variance is : 3.3077234513596054
10
3 Statistical Ensembles
3.1 Statistical Coin Tossing
Perform a numerical experiment of coin toss to show that, for very large number of
trials, the probability of obtaining head is 12
import numpy as np
import random
import matplotlib . pyplot as plt
return x / N_val
Pro_val = probab ( N )
11
3.3 Output
12
3.4 Statistical Ball Choosing
In a box there is 5 red and 7 white balls.
1. One ball is taken out of the box randomly. Get the probability of obtaining
the ball as red, with simulation.
2. two balls are taken randomly. Obtain the probability of obtaining
(a) both the ball as red, with simulation.
(b) one ball red and another ball white, with simulation
Verify all the results with the theoretical results.
# Single Choice
import numpy as np
import random
N_red = 0
if stimul_arr [0] == 0 :
N_red += 1
# Multiple Choice
import numpy as np
import random
total_throws = 10000
stimul_arr = np . array ([0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,1 ,1])
frequency = np . zeros (3)
13
for i in range ( total_throws ) :
random . shuffle ( stimul_arr )
frequency [ out ] += 1
3.6 Output
Probability of getting red ball : 0.4235
Theoretical probability of getting red ball : 0.4166666666666667
14
3.7 Statistical Dice Throw
Two dices are thrown. Obtain the probability of getting the
1. point 3 on both of the dices, with simulation.
2. sum of the points on the dices as 7, with simulation.
3. point 3 on first dice and point 4 on second dice, with simulation.
Verify all the results with the theoretical results.
total_throws = 10000
dice_options = np . array ([1 ,2 ,3 ,4 ,5 ,6])
N_three = 0
N_seven = 0
N_choice = 0
if ( out1 + out2 ) == 7:
N_seven += 1
15
3.9 Output
Probability of 3 s on both dice : 0.0291
Probability of sum of outcomes as 7 : 0.1597
Probability of 3 on first dice and 4 on second dice : 0.0249
16
4 Probability Distributions
4.1 Binomial Distribution
Binomial Distribution Simulate a coin toss experiment N times. Obtain the prob-
abilities of obtaining head in n=1,2,...,N trial. Plot the probabilities respect to n.
Compare the results with
n N −n
N 1 1
= (1)
n 2 2
Take N = 10 first. Now increase N to show that the probability distribution
converges to the Gaussian distribution.
import numpy as np
import matplotlib . pyplot as plt
N = 100
N_stat = 200
def toss ( n_toss ) :
n = 0
if n_head == n_toss :
n += 1
return n / N_stat
n = np . arange (1 , N +1 ,1)
17
4.3 Output
18
4.4 Different Variates
10. Obtain a set of N = 5000 number of
1. Gaussian variate random numbers using the module random.gauss
2. exponential variate random numbers using the module random.expovariate
3. beta variate random numbers using the module random.betavariate
import numpy as np
import matplotlib . pyplot as plt
import random
# Gaussian variate
N = 5000
mu , sig = 1 , 10
T = np . zeros (( N ) )
for i in range ( N ) :
T [ i ] = random . gauss ( mu , sig )
# Exponential Variate
N = 5000
lam = 2.0 # decay parameter
T = np . zeros (( N ) )
for i in range ( N ) :
T [ i ] = random . expovariate ( lam )
# Beta variate
19
N = 5000
par1 , par2 = 0.5 , 0.6
T = np . zeros (( N ) )
for i in range ( N ) :
T [ i ] = random . betavariate ( par1 , par2 )
20
4.6 Output
21
22
5 Transformation Between Distributions
5.1 Different Transformations
Craete N number of uniform random numbers between [0, 1] as X = x0 , x1 , ..., xN −1 .
Transform these numbers with the rule Y = g(X) for each member of X to obtain the
set of numbers Y = y0 , y1 , ..., yN −1 . Perform the below tasks (a) Get the histogram
plot of Y (b) Obtain the probability distribution of Y using program-4. with proper
dx. Plot this probability distribution (Not histogram plot) for
√
1. Y = X
−ln(λx)
2. Y = λ
3. Y = X 2
1
4. Y = −X 3
5. Y = sin(X)
N_bins = 100
23
for i in range ( len ( arr ) ) :
while (k < N_bins ) :
low = lower_bound + k * bin_size
upp = lower_bound + ( k +1) * bin_size
if low <= arr [ i ] < upp :
counter [ k ] += 1
k = 0
break
else :
k += 1
continue
’’’
# Further reducing computation
temp = np . copy ( arr )
temp = np . sort ( temp )
k = 0
arr_base = 0
while (k < N_bins ) :
s = 10
dist = np . random . uniform (0 ,1 ,100000)
y = [ _ **2 for _ in dist ]
freq_plot ( y )
24
5.3 Output
25
26
6 Monte Carlo Integrations
6.1 Problem 1
Write a Python function to perform the following integration
Z b
f (x)dx
a
The Python function must have f, a, b, N are the arguments. Here N is the
number of random numbers. Check your Python function performing the following
integration. Z 1
2x3 ln(x2 + 1)dx
0
Compare with the exact result 4.
import numpy as np
import matplotlib . pyplot as plt
low_lim , upp_lim = 0 ,1
N = 400000
x = np . random . uniform (0 ,1 , N )
y = f(x)
27
6.3 Output
Value of Integration by MCI method : 0.2507006324463914
Result by Simpson Integration : 0.2500000008484694
28
6.4 Problem 2
Use the Python function in prob-1 to calculate the following integration
Z 2
sin2 x
2
dx
0 1 + sin x
low_lim = 0
upp_lim = 2
f = lambda x : np . sin ( x ) **2 / (1+ np . sin ( x ) **2)
N = 10000
def MCI (f ,a ,b , N ) :
x = np . random . uniform (a ,b , N )
y = f(x)
integ = (b - a ) * np . mean ( y )
return integ
6.6 Output
The value of the integration is : 0.6686143463854288
The exact answer is 0.6679713348808409
29
6.7 Problem 3
Use the Python function in prob-1 to calculate the following integration
Z x
2 2
erf (x) = √ e−t dt
π 0
low_lim = -3
upp_lim = 3
x = np . arange ( -3 ,3 ,0.1)
N = 100000
def MCI ( b ) :
30
6.9 Output
31
6.10 Problem 4
Use the Python function in prob-1 to calculate the following integration
1
g(x) = 1 − erf √
2 x
low_lim = -3
upp_lim = 3
x = np . arange (0.5 ,3 ,0.1)
N = 100000
def MCI ( b ) :
plt . plot (x , g )
plt . grid ()
plt . show ()
32
6.12 Output
33
6.13 Problem 5
Use the Python function in prob-1 to calculate the following integration
3 Z T
x4 ex
T TD
Cv (T ) = K dx
TD 0 (ex − 1)2
K = 75.0
Td = 1.0
return int
plt . plot ( T / Td , Cv , ’o ’)
plt . show ()
34
6.15 Output
35
7 Random Walk
7.1 Problem 1
Simulate random walk of 20 steps in one and two dimensions. If the mean square
displacement from origin of a particle executing random walk, is < x2 >, then show
that
⟨x2 ⟩ ∼ t
for large number of ensemble average. Here t is the time steps of random walk.
import numpy as np
import random
import matplotlib . pyplot as plt
step_size = 1
def mean ( t ) :
time_step = t
displacement = np . zeros (500)
36
means = mean ( times )
37
7.3 Output
38
7.4 Problem 2
Simulate random walk of 20 steps in one dimension. Show that the probability
distribution for final position at 0, 1, ..., 19, 20 in left and right side satisfies the
relation N
N 1
n!(N − n)! 2
for large number of ensemble average. Here n is number of steps either in left or
right side.
step_size = 1
def mean ( t ) :
time_step = t
displacement = np . zeros (500)
39
mean_displacement = np . sum ( displacement ) / 500
return mean_displacement
40
7.6 Output
41
8 Quantum Statistics Plots
8.1 Plot 1
The energy distribution functions of particles are given by
1
f (ϵ) =
ϵ−µ
exp KB T
+a
Here, for a = −1, 0, 1 the f (ϵ) are called as BE, MB and FD distribution functions
respectively. Plot three distribution functions respect to x = Kϵ−µ
BT
for the ranges 0.35 ≤ x ≤ 3.0, −1x3 and −3.0 ≤ x ≤ 3.0 respectively with
δx = 0.05 in single graph. Show x and y axes.
import numpy as np
import matplotlib . pyplot as plt
a1 , a2 , a3 = -1 , 0 ,1
42
8.3 Output
43
8.4 Plot 2 : FD Distribution
The energy distribution functions of particles are given by
1
f (ϵ) =
ϵ−µ
exp KB T
+1
µ
Plot f (ϵ) in the range 0 ≤ µϵ ≤ 5.0 with = 0.02 for KB T
= 1, 2, 10, 100 in same
graph. Put proper x-label and y-label and plot-labels.
def f (x , chem ) :
return 1/( np . exp ( chem *( x -1) ) +1)
44
8.6 Output
45