You are on page 1of 48

Statistical Mechanics - Python Implementation

Jeet Bhattacharjee

Department of Physics, Semester V

Scottish Church College, Kolkata

March 4, 2024

1
Contents
1 Introduction 1

2 Plotting of Random Numbers 2


2.1 Problem 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.4 Problem 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.5 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.7 Problem 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.8 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.9 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.10 Problem 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.11 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.12 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.13 Problem 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.14 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.15 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.16 Problem 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.17 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.18 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.19 Problem 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.20 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.21 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

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

6 Monte Carlo Integrations 27


6.1 Problem 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.4 Problem 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.5 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.7 Problem 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.8 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.9 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.10 Problem 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
6.11 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 32
6.12 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.13 Problem 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.14 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.15 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

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

8 Quantum Statistics Plots 42


8.1 Plot 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
8.2 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 42
8.3 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
8.4 Plot 2 : FD Distribution . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.5 Python Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

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.

2.2 Python Implementation

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].

2.5 Python Implementation

# Plot of random integers between 1 and 100

import numpy as np
import matplotlib . pyplot as plt

x = np . random . randint (1 ,101 ,1000)

plt . hist (x ,500 , color = ’g ’ , edgecolor = ’k ’)


plt . title ( " Uniform random integers plot " )
plt . show ()

2.6 Output

3
2.7 Problem 3
Generate 1000 uniform random integers. Get the mean and median of these num-
bers.

2.8 Python Implementation

# Mean and median

import numpy as np
import matplotlib . pyplot as plt

sample = np . random . uniform (0 ,100 ,1000)

def mean ( dist ) :


men = 0
for _ in range ( len ( dist ) ) :
men += dist [ _ ]

men = men / len ( dist )

return men

def median ( dist ) :


n = len ( dist )
med = 0

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

print ( f " The mean of the sample is : { mean ( sample ) } " )


print ( f " The median of the sample is : { median ( sample ) } " )

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

2.11 Python Implementation

# Bin size adjustment

import numpy as np
import matplotlib . pyplot as plt

N , a , b , dx = 5000 , -1.3 , 1.3 , 0.05

# N_bins = int (( b - a ) / dx )
x = np . random . uniform (a ,b , N )
N_bins = np . arange ( min ( x ) , max ( x ) , dx )

plt . hist (x , N_bins , edgecolor = ’k ’)


plt . show ()

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.

2.14 Python Implementation

#N - th moment

import numpy as np
import matplotlib . pyplot as plt

x = np . random . uniform (0 ,1 ,1000)

def n_moment ( x_dist , n ) :


mean = np . mean ( x )
sig_x_n = np . zeros (( len ( x_dist ) ) )

sig_x_n = ( np . abs ( x_dist - ( np . ones ( len ( x_dist ) ) * mean


) ) ** n ) / len ( x_dist )

return sig_x_n

sig1 = n_moment (x ,1)


sig2 = n_moment (x ,2)
sig3 = n_moment (x ,3)
sig4 = n_moment (x ,4)

plt . hist ( sig1 ,50)


plt . hist ( sig2 ,50)
plt . hist ( sig3 ,50)
plt . hist ( sig4 ,50)
plt . show ()

6
2.15 Output

7
2.16 Problem 6
Write a function to obtain the mean and variance of a given set of numbers.

2.17 Python Implementation

# Mean and Variance


import numpy as np
import matplotlib . pyplot as plt

sample = np . random . uniform (0 ,100 ,1000)

def mean ( dist ) :


men = 0
for _ in range ( len ( dist ) ) :
men += dist [ _ ]

men = men / len ( dist )

return men

def Variance ( dist ) :

mean_val = np . ones ( len ( dist ) ) * mean ( dist )

variance = np . sum (( dist - mean_val ) **2) / len ( dist )

return variance

print ( f " The mean of the sample is : { mean ( sample ) } " )


print ( f " The Variance of the sample is : { Variance ( sample )
}")

Mean = np . mean ( sample )


Variance = np . std ( sample ) **2

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 [−π, π]

1. Using program-6 obtain the mean (µ) and variance (σ 2 ) of X.

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.

For each histogram plot, take bin width appropriately.

2.20 Python Implementation

import numpy as np
import matplotlib . pyplot as plt

x = np . random . uniform ( - np . pi , np . pi ,6000)

Mean = np . mean ( x )
Variance = np . std ( x ) **2
Median = np . median ( x )

print ( " Mean is : " , Mean )


print ( " Variance is : " , Variance )
print ( " Variance is : " , Variance )

n = 200
mean = []
Given = []

for i in range (6000) :


X = np . random . choice (x , n )
mean . append ( np . mean ( X ) )
Given . append (( np . mean ( X ) - Mean ) /( Variance * n ) )

plt . hist ( mean ,200 , color = ’r ’)


plt . title ( " The Mean " )
plt . show ()

plt . hist ( Given ,200 , color = ’k ’)


plt . title ( r " $ \ frac { < X_n > - \ mu }{\ sigma ^2 n } $ " )
plt . show ()

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

3.2 Python Implementation

# Statistical Coin Tossing

import numpy as np
import random
import matplotlib . pyplot as plt

rand_var = np . array ([0 ,1])

def probab ( N_val ) :


x = 0
for i in range ( N_val ) :
outcome = random . choice ( rand_var )
if outcome ==1:
x += 1

return x / N_val

probab = np . vectorize ( probab )

N = np . arange (1000 ,100000 ,100)

Pro_val = probab ( N )

plt . plot (N , Pro_val )


plt . plot (N ,0.5* np . ones ( len ( N ) ) , ’ -. ’)
plt . ylim (0.65 ,0.45)
plt . show ()

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.

3.5 Python Implementation

# Statistical Ball Choosing

# Single Choice
import numpy as np
import random

stimul_arr = np . array ([0 ,0 ,0 ,0 ,0 ,1 ,1 ,1 ,1 ,1 ,1 ,1])


total_throws = 10000

N_red = 0

for i in range ( total_throws ) :


random . shuffle ( stimul_arr )

if stimul_arr [0] == 0 :
N_red += 1

print ( f " Probability of getting red ball : { N_red /


total_throws } " )
print ( f " Theoretical probability of getting red ball :
{5/12} " )

# 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 )

out = stimul_arr [0] + stimul_arr [1]

frequency [ out ] += 1

print ( f " Probability of getting 2 red balls : { frequency


[2]/ total_throws } " )
print ( f " Probability of getting 1 red ball and 1 white
ball : { frequency [1]/ total_throws } " )
print ( f " Probability of getting 2 white balls : { frequency
[0]/ total_throws } " )

3.6 Output
Probability of getting red ball : 0.4235
Theoretical probability of getting red ball : 0.4166666666666667

Probability of getting 2 red balls : 0.1481


Probability of getting 1 red ball and 1 white ball : 0.5275
Probability of getting 2 white balls : 0.3244

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.

3.8 Python Implementation


# Dice Throwing
import numpy as np
import random

total_throws = 10000
dice_options = np . array ([1 ,2 ,3 ,4 ,5 ,6])

N_three = 0
N_seven = 0
N_choice = 0

for i in range ( total_throws ) :

random . shuffle ( dice_options )


out1 = dice_options [0]

random . shuffle ( dice_options )


out2 = dice_options [0]

if out1 == 3 and out2 == 3:


N_three += 1

if ( out1 + out2 ) == 7:
N_seven += 1

if out1 == 3 and out2 == 4:


N_choice += 1

print ( f " Probability of 3 s on both dice : { N_three /


total_throws } " )
print ( f " Probability of sum of outcomes as 7 : { N_seven /
total_throws } " )
print ( f " Probability of 3 on first dice and 4 on second
dice : { N_choice / total_throws } " )

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.

4.2 Python Implementation


# Binomial Distribution

import numpy as np
import matplotlib . pyplot as plt

N = 100
N_stat = 200
def toss ( n_toss ) :
n = 0

for __ in range ( N_stat ) :


n_head = 0
for _ in range ( N ) :

choice = np . random . uniform ()

if choice < 0.5:


n_head += 1

if n_head == n_toss :
n += 1

return n / N_stat

toss = np . vectorize ( toss )

n = np . arange (1 , N +1 ,1)

plt . plot (n , toss ( n ) )


plt . xlim (0 , N +1)
plt . show ()

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

4.5 Python Implementation


# Variates

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 )

plt . hist (T ,50 , edgecolor = ’k ’)


plt . show ()

# Exponential Variate

N = 5000
lam = 2.0 # decay parameter

T = np . zeros (( N ) )

for i in range ( N ) :
T [ i ] = random . expovariate ( lam )

plt . hist (T ,50 , edgecolor = ’k ’)


plt . show ()

# 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 )

plt . hist (T ,50 , edgecolor = ’k ’)


plt . show ()

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)

5.2 Python Implementation


import numpy as np
import matplotlib . pyplot as plt

def freq_plot ( arr ) :

lower_bound = min ( arr )


upper_bound = max ( arr )

N_bins = 100

bin_size = ( upper_bound - lower_bound ) / N_bins

bins = np . zeros (( N_bins + 1) )

for i in range ( N_bins + 1) :


bins [ i ] = lower_bound + i * bin_size

counter = np . zeros (( N_bins ) )


’’’
for i in range ( len ( arr ) ) :
for j in range ( N_bins ) :
if bins [ j ] <= arr [ i ] < bins [ j +1]:
counter [ j ] += 1

# Without using bins array


k = 0

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 ) :

low = lower_bound + k * bin_size


upp = lower_bound + ( k +1) * bin_size

for i in range ( arr_base , len ( temp ) ) :


if low <= temp [ i ] < upp :
counter [ k ] += 1

elif temp [ i ] >= upp :


arr_base = i
break
k += 1

bin_plot = np . zeros (( N_bins ) )

for i in range ( N_bins ) :


bin_plot [ i ] = ( bins [ i ] + bins [ i +1]) *0.5

plt . scatter ( bin_plot , counter )


# plt . ylim (0 ,200)
plt . show ()

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.

6.2 Python Implementation


# Integration

import numpy as np
import matplotlib . pyplot as plt

low_lim , upp_lim = 0 ,1
N = 400000

f = lambda x : (2* x **3) * np . log (( x **2) +1)


p = lambda x : 1/( upp_lim - low_lim )
q = lambda x : 1/ np . sqrt (2* np . pi ) * np . exp ( -(x -1) **2)

x = np . random . uniform (0 ,1 , N )
y = f(x)

integ = ( upp_lim - low_lim ) / N * np . sum ( y )


print ( f " Value of Integration by MCI method : { integ } " )

from scipy . integrate import simps

f = lambda x : (2* x **3) * np . log (( x **2) +1)


x_lin = np . linspace (0 ,1 ,1000)
y_sim = f ( x_lin )

print ( f " Result by Simpson Integration : { simps ( y_sim ,


x_lin ) } " )

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

Compare with exact value


π 1 √ 
2 − √ − √ tan−1 2tan2
2 2

6.5 Python Implementation


# Sinusoidal Integration
import numpy as np
import matplotlib . pyplot as plt

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

print ( f " The value of the integration is : { MCI (f , low_lim ,


upp_lim , N ) } " )
print ( f " The exact answer is {2 -( np . pi /2**0.5) -(1/2**0.5) *
np . arctan ((2**0.5) * np . tan (2) ) } " )

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

6.8 Python Implementation


# Error Function
import numpy as np
import matplotlib . pyplot as plt

low_lim = -3
upp_lim = 3
x = np . arange ( -3 ,3 ,0.1)

N = 100000

def MCI ( b ) :

f = lambda t : np . exp ( - t **2)


xval = np . random . uniform (0 ,b , N )
y = f ( xval )

integ = (2/ np . sqrt ( np . pi ) ) *( b -0) * np . mean ( y )


return integ

MCI = np . vectorize ( MCI )


erf = MCI ( x )

plt . plot (x , erf )


plt . grid ()
plt . xlabel ( " x -->" )
plt . ylabel ( " f ( x ) -->" )
plt . show ()

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

6.11 Python Implementation


# Complimentary Error Function
import numpy as np
import matplotlib . pyplot as plt

low_lim = -3
upp_lim = 3
x = np . arange (0.5 ,3 ,0.1)

N = 100000

def MCI ( b ) :

f = lambda t : np . exp ( - t **2)


xval = np . random . uniform (0 ,b , N )
y = f ( xval )

integ = (2/ np . sqrt ( np . pi ) ) *( b -0) * np . mean ( y )


return integ

MCI = np . vectorize ( MCI )


erf = MCI (1/(2*( x **0.5) ) )
g = 1 - erf

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

6.14 Python Implementation


# Specific Heat of Solids
import numpy as np
import matplotlib . pyplot as plt

K = 75.0
Td = 1.0

def MCI ( T_val ) :


N = 5000000

f = lambda x : K *(( T_val / Td ) **3) *(( x **4) * np . exp ( x ) ) /((


np . exp ( x ) -1) **2)

x = np . random . uniform (0 , Td / T_val , N )


y = f(x)

int = (( Td / T_val ) -0) * np . sum ( y ) / N

return int

MCI = np . vectorize ( MCI )

T = np . arange (2.0 ,17.0+0.5 ,0.5)


Cv = MCI ( T )

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.

7.2 Python Implementation


# Random Walk 1 D

import numpy as np
import random
import matplotlib . pyplot as plt

step_size = 1

def mean ( t ) :
time_step = t
displacement = np . zeros (500)

for _ in range (500) :

initial_pos = np . array ([0])

pos = initial_pos . copy ()

for i in range ( time_step ) :

choice = random . choice ([1 , -1])


choice = np . array ( choice )
pos = pos + choice

displacement [ _ ] = np . sqrt ( ( pos [0] - initial_pos [0])


**2 )

mean_displacement = np . sum ( displacement ) / 500


return mean_displacement

mean = np . vectorize ( mean )

times = range (1 ,1001)

36
means = mean ( times )

plt . plot ( times , means )


plt . xlabel ( " t -->" )
plt . ylabel ( " Mean displacement , s -->" )
plt . show ()

plt . plot ( np . log ( times ) , np . log ( means ) )


plt . xlabel ( " log ( t ) -->" )
plt . ylabel ( " log ( x ) -->" )
plt . grid ()
plt . show ()

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.

7.5 Python Implementation


# Random Walk 2 D
import numpy as np
import matplotlib . pyplot as plt
import matplotlib . animation

step_size = 1

def mean ( t ) :
time_step = t
displacement = np . zeros (500)

for _ in range (500) :

initial_pos = np . array ([0 ,0])

pos = initial_pos . copy ()

for i in range ( time_step ) :

choice = np . random . uniform ()

if choice >= 0.75:


pos [1] -= step_size
elif 0.75 > choice >= 0.5:
pos [1] += step_size
elif 0.5 > choice >= 0.25:
pos [0] += step_size
elif 0.25 > choice >= 0:
pos [0] -= step_size

displacement [ _ ] = np . sqrt ( ( pos [0] - initial_pos [0])


**2 + ( pos [1] - initial_pos [1]) **2 )

39
mean_displacement = np . sum ( displacement ) / 500
return mean_displacement

mean = np . vectorize ( mean )

times = np . arange (1000 ,2000 ,50)


log_t = np . log ( times )
means = mean ( times )
log_means = np . log ( means )
t = np . linspace (1000 ,2000 ,10000)
plt . scatter ( times , means )
plt . plot (t ,( means [4]/( times [4]**0.5) ) * t **0.5 , ’ -- ’)

plt . xlabel ( " times of enumeration , t -->" )


plt . ylabel ( " Mean displacement , d --> " )
plt . show ()

plt . scatter ( log_t , log_means )


plt . show ()

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.

8.2 Python Implementation


# Quantum Statistics Plots

import numpy as np
import matplotlib . pyplot as plt

a1 , a2 , a3 = -1 , 0 ,1

x1 = np . arange (0.35 ,3.05 ,0.05)


x2 = np . arange ( -1.0 ,3.05 ,0.05)
x3 = np . arange ( -3.0 ,3.05 ,0.05)

plt . plot ( x1 ,1/( np . exp ( x1 ) + a1 ) , label = " BE dist " )


plt . plot ( x2 ,1/( np . exp ( x2 ) + a2 ) , label = " MB dist " )
plt . plot ( x3 ,1/( np . exp ( x3 ) + a3 ) , label = " FD dist " )
plt . grid ()
plt . legend ( loc = ’ best ’)
plt . axvline (0.0 , c = ’m ’ , ls = ’ -- ’)
plt . show ()

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.

8.5 Python Implementation


# FD Distribution
import numpy as np
import matplotlib . pyplot as plt

chem_parm = [1 ,2 ,10 ,100]

x = np . arange (0.0 ,5.02 ,0.02)

def f (x , chem ) :
return 1/( np . exp ( chem *( x -1) ) +1)

for i in range ( len ( chem_parm ) ) :


plt . plot (x , f (x , chem_parm [ i ]) , label = r " $ \ frac {\ mu }{ K_B T }
= $ % s " % chem_parm [ i ])

plt . legend ( loc = ’ best ’)


plt . axhline (0.5 , ls = ’ -- ’)
plt . show ()

44
8.6 Output

45

You might also like