CHEM 145 Python Lab 1C
CHEM 145 Python Lab 1C
TASK 1: Work with the Maxwell-Boltzmann Speed Distribution for a gas. There are several sub tasks here.
Plot the Maxwell-Boltzmann speed distribution for H2 and N2 gases at a temperature of 150 K. Be sure to
label your axes (including units) and also include a legend so we know which plot is which. It is probably
good to input a bunch of useful paramters and then to create a function called MBSD or something similar
that accepts an array of speeds v, the mass of the molecule of interest m, and the temperature T in Kelvins.
When you make your plots, you need to decide on the range of the speed array, and it may be useful to
have it go from a speed of 0 m/s to a speed twice or three times the most probable (peak) speed. You can
figure out the most probable speed analytically using equations in the notes for the MBSD.
The MBSD is normalized, meaning that the integrated area is 1. Check that this is true using numerical
integration. To numerically integrate the function with respect to v, you will make a bunch of tiny boxes that
approximate the function. A simple way to do this is to multiply the function's value at each of the sampled
points in the array by the speed interval along the x axis so you have a bunch of boxes and to then add up
the area of all the boxes. Since the interval between samples along the x-axis is constant for all boxes,
finding the area under the curve is equivalent to summing the function's value at all points and then
multiplying the sum by the speed interval along the x axis like this... np.sum(fv1)*(v[2]-v[1]). Print out a
statement that "The integrated area of the MBSD for H2 at 150 K is XXX." and also "The integrated area of
the MBSD for N2 at 150 K is YYY."
To numerically calculate a property of a normalized distribution you can do an integral of that variable times
the distribution.
The mean speed is $v_{avg} = \int_0^\infty{f(v)vdv}$. Calculate the mean speed numerically for H2 and
N2. Print out a statement indicating "The mean speed for H2 at 150 K is XXX m/s." and "The mean
speed for N2 at 150 K is YYY m/s.".
The mean square speed is $v_{avg} = \int_0^\infty{f(v)v^2dv}$. Calculate the root mean square speed
numerically for H2 and N2 (square root of the mean square speed). Print out a statement indicating
"The RMS speed for H2 at 150 K is XXX m/s." and "The RMS speed for N2 at 150 K is YYY m/s."
Use the function np.argmax to numerically calculate the peak speed for H2 and N2. Read about how the
function works. Write a statement to print "The peak speed for H2 at 150 K is XXX m/s." and "The peak
speed for N2 at 150 K is YYY m/s."
For the mean speeds, root mean square speeds, and peak speeds, did your numerical calculations agree
with the results you get when doing an analytical calcaulation from the equations we derived in class? Print
a statement indicating "The numerical and analytical speeds matched." or "The numerical and analytical
speeds did not match."
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 1/11
10/26/2020 Lab1c_assignment
In [26]:
import numpy as np
import matplotlib.pyplot as plt
def MBSD(v,m,T):
return 4 * pi * ((m/(2*pi*kB*T))**(3/2)) * (v**2) * np.exp((-m*(v**2)/(2*kB*T
)))
H2 = MBSD(v,mH2,150)
N2 = MBSD(v,mN2,150)
ax = plt.axes()
ax.plot(v, H2, label='MBSD for H2')
ax.plot(v, N2, label='MBSD for N2')
legend = ax.legend(loc='upper left', shadow=True, fontsize='large')
plt.xlabel('Velocity (m/s)')
plt.ylabel('Probability')
# The MBSD is normalized, meaning that the integrated area is 1. Check that this is
true using numerical
# integration. To numerically integrate the function with respect to v, you will ma
ke a bunch of tiny boxes that
# approximate the function. A simple way to do this is to multiply the function's v
alue at each of the sampled points
# in the array by the speed interval along the x axis so you have a bunch of boxes
and to then add up the area of all
# the boxes. Since the interval between samples along the x-axis is constant for al
l boxes, finding the area under the
# curve is equivalent to summing the function's value at all points and then multip
lying the sum by the speed interval
# along the x axis like this... np.sum(fv1)*(v[2]-v[1]). Print out a statement that
"The integrated area of the MBSD
# for H2 at 150 K is XXX." and also "The integrated area of the MBSD for N2 at 150
K is YYY."
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 2/11
10/26/2020 Lab1c_assignment
sumH2 = np.sum(H2*(v[2]-v[1]))
sumN2 = np.sum(H2*(v[2]-v[1]))
print('The integrated area of the MBSD for H2 at 150 K is {:.5f}'.format(sumH2))
print('The integrated area of the MBSD for N2 at 150 K is {:.5f}'.format(sumN2))
MS_H2 = np.sum(H2*v)*(v[2]-v[1])
MS_N2 = np.sum(N2*v)*(v[2]-v[1])
# Calculate the root mean square speed numerically for H2 and N2 (square root of th
e mean square speed). Print out a
# statement indicating "The RMS speed for H2 at 150 K is XXX m/s." and "The RMS spe
ed for N2 at 150 K is YYY m/s."
RMS_H2 = (np.sum(H2*v**2)*(v[2]-v[1]))**.5
RMS_N2 = (np.sum(N2*v**2)*(v[2]-v[1]))**.5
# Use the function np.argmax to numerically calculate the peak speed for H2 and N2.
Read about how the function works.
# Write a statement to print "The peak speed for H2 at 150 K is XXX m/s." and "The
peak speed for N2 at 150 K is YYY
# m/s."
# For the mean speeds, root mean square speeds, and peak speeds, did your numerical
calculations agree with the results
# you get when doing an analytical calcaulation from the equations we derived in cl
ass? Print a statement indicating
# "The numerical and analytical speeds matched." or "The numerical and analytical s
peeds did not match."
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 3/11
10/26/2020 Lab1c_assignment
TASK 2: Create plots of gas compressibility vs pressure for the van der Waals gas equation of state for N2 gas
at T=150K, 225K, 400K. Be sure to label your axes (including units) and also include a legend so we know which
plot is which. There are lots of ways to do this, but here are some hints about one way.
It can be tricky with the vdW model to plug directly into $Z=\frac{PV}{nRT}$ since it isn't easy to get volume
in terms of pressure. The instructions below are a way around this problem.
Define a vector of volumes V from 0.00004 to 0.01 with ~1000 points in it using np.linspace.
Define a function called Pvdw that returns an array of vdW pressure values P when provided the array of
volumes V and the values of n, T, a, b. (Look up the parameters a and b and be careful with units.) You can
use n=1 if you like.
Calculate gas compressibility Z by multiplying P from above by V/nRT where V are the corresponding
volumes. Do this for each of the three temperatures and create an overlay plot for all three temperatures.
Make your plot of Z vs P and set the y limits to be around 0,4 and the x-limits (pressure) to be around
0,10^8 Pa. Label your plot axes, including units if applicable.
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 4/11
10/26/2020 Lab1c_assignment
In [28]:
import numpy as np
import matplotlib.pyplot as plt
n = 1 # mol
RL = 0.082057 # L*atm / K*mol
Rm3 = 8.31 # J / K*mol
a = 1.35082 # atm*L^2 / mol^2
b = 0.0387 # L / mol
Vm3 = np.linspace(.00004,.01,1000) # Volume in m^3
VL = np.linspace(0.04,10,1000) # Volume in L
def Pvdw(V,n,T):
return ((n*RL*T)/(V-n*b)) - (a*(n**2)/(V**2))
def gas_comp(P,V,n,T):
return ((P*V)/(n*Rm3*T))
Z_150 = gas_comp(P_150,Vm3,1,150)
Z_225 = gas_comp(P_225,Vm3,1,225)
Z_400 = gas_comp(P_400,Vm3,1,400)
ax = plt.axes()
plt.title('Gas compressibility z vs. Pressure (Pa)')
plt.xlim(0,1e8)
plt.ylim(0,4)
ax.plot(P_150,Z_150,label='T=150')
ax.plot(P_225,Z_225,label='T=225')
ax.plot(P_400,Z_400,label='T=400')
plt.xlabel('Pressure (Pa)')
plt.ylabel('Gas compressibility z')
legend = ax.legend(loc='lower right', shadow=True, fontsize='large')
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 5/11
10/26/2020 Lab1c_assignment
TASK 3: Plot the Lennard-Jones potential for H2 and N2. Use y-limits of -2e-21,4e-21 J and x-limits of 0,8e-10
m. Be sure to label your axes (including units) and also include a legend so we know which plot is which.
In [115]:
import numpy as np
import matplotlib.pyplot as plt
R = np.linspace(1e-11,8e-10,100) # m
eps_H2 = 37 * 1.38e-23 # kg*m^2 / s^2
eps_N2 = 95.1 * 1.38e-23
sig_H2 = 293e-12 # m
sig_N2 = 370e-12
def LJP(R,eps,sig):
return 4*eps * (((sig/R)**12)-((sig/R)**6))
LJP_H2 = LJP(R,eps_H2,sig_H2)
LJP_N2 = LJP(R,eps_N2,sig_N2)
ax = plt.axes()
plt.title('Potential energy (J) vs. Radius (m)')
plt.xlim(0,8e-10)
plt.ylim(-2e-21,4e-21)
ax.plot(R,LJP_H2,label='H2')
ax.plot(R,LJP_N2,label='N2')
plt.xlabel('R (m)')
plt.ylabel('Potential energy (J)')
legend = ax.legend(loc='upper left', fontsize='large')
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 6/11
10/26/2020 Lab1c_assignment
TASK 4: The (gas-liquid) critical point is a pressure, temperature point above which there ceases to be a
distinction between liquids and gases. Above the critical point pressure and temperature, the substance will fill
its container like a gas but can have a high density like a liquid. Most introductory chemistry courses merely
point out that there is such a thing as a liquid-gas critical point or that super-critical fluids (like supercritical CO2)
can be useful for a range of chemical processes like decaffeination. Guess what? We already have a nice
equation that can give you the critical point--that's right, your old friend the van der Waals model of a nonideal
gas!
The plot below shows pressure vs volume plots at constant temperature (these are called isotherms) with the
vdW model for N2. If you look closely, you can see that the bottom plots have some wiggles (from left to right, a
curve goes down then up, then down again) and the upper plots don't (from left to right, they just go down) and
that somewhere in between there is a transition between those two regimes. That transition occurs at the critical
temperature. Below the critical temperature, these wiggles are interpreted as indicating that there can be
coexistence of a liquid and a gas just like how we draw the situation on our P vs T phase diagrams. Sometimes
scientists sort of draw a straight line across the wiggly part to indicate the phase transition since the wiggles
themselves aren't meaningful, but we won't need to worry about that here.
In this task you have to do something on a separate page (e.g., with a pencil and paper) and then you have to
do some coding. Submit both.
Task 4a On a separate paper that you are to submit with this assignment, do the following. First Recognize that
the critical temperature is the temperature where oscillations are just starting. The isotherm that shows this will
have at Tc a slope of zero, with $\frac{dP}{dV} = 0$. At the same time, when the wiggles are just starting there is
also an "inflection point" where the curve goes from concave up to concave down, meaning that at Tc the
second derivative will also be zero, with $\frac{d^2P}{dV^2}=0$. Your job is to derive the value of Tc. Here are
instructions.
Take the derivative of the vdW equation $P=\frac{nRT}{V-nb}-a\frac{n^2}{V^2}$ with respect to volume and
set it equal to zero.
Take the second derivative of the vdW equation with respect to volume and also set it equal to zero.
Solve those two equations to find the value of Vc... you should get $V_c=3nb$.
Substitute your value of $V_c$ into the equation you got from $\frac{dP}{dV} = 0$ and then you can solve
for $T_c$. You should get $T_c=\frac{8a}{27bR}$.
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 7/11
10/26/2020 Lab1c_assignment
Task 4b For your coding assignment, do the following. Things will probably be easier if you are careful to use SI
units for everything including the vdW constants. That means it will be easier to use units of m, Kg, mol, K, Pa,
N, J, etc., rather than g, atm, etc.
Create a function that can return a set of pressures based on the vdW gas model when given a 1-D array of
volumes, a temperature, and the vdW a, b parameters.
Choose 1 mole of Xenon gas. Find the a and b vdW paramters for Xenon and enter them. Then create an
array of volumes with ~1000 points that go from approximately 0.0001 m^3 to 0.0005 m^3. For yourself
(don't need to show for your submitted assignment) just check that you can use your function to plot vdW
pressure vs volume for a temperature of interest. For this, you could choose your analytical value of Tc if
you wish.
Next, create a plot like the one in this markdown cell, but for the gas Xe. It should include few isotherms
with temperatures below the critical temperature and a few with temperatures above the critical
temperature. A nice way to do this is to create a loop that will plot the vdW isotherm where each iteration of
the loop uses a different temperature. I used 11 tempeartures in my plot, above, for N2, over the range 110-
210 K. I used a log-x plot where the x-axis is plotted logarithmically but the y-axis is plotted linearly, using
the function np.semilogx, rather than our usual linear/linear plots created using np.plot, but this isn't
essential.
Choose the x-limits and y-limits of your plot to zoom in on a region roughly like the one I did that shows the
transition of wiggles to no wiggles. The functions plt.xlim and plt.ylim are useful for this. I used plt.ylim(0,
2e7) and plt.xlim(5e-5, 3e-4) in my plot, but you will have to find appropriate limits for your plot. Also, be
sure to label your x and y axes and indicate the units.
Examine your plot to find the temperature at which the wiggles seem to disappear. Print out the following
statement. "My analytical result predicted Tc = XXX K and inspecting a plot of the vdW isotherms provided
an approximate value of Tc = YYY K."
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 8/11
10/26/2020 Lab1c_assignment
In [93]:
import numpy as np
import matplotlib.pyplot as plt
# Create a function that can return a set of pressures based on the vdW gas model w
hen given a 1-D array of
# volumes, a temperature, and the vdW a, b parameters.
V = np.linspace(.0001,.0005,1000) # m^3
T = 290 # K
a = 4.192e-1 # Pa m^6 mol^-2
b = 0.05156e-3 # m^3 mol^-1
n = 1 # mol
R = 8.31
def pressure(n,V,T,a,b):
return n*R*T/(V-n*b) - (a*n**2)/(V**2)
vdWP_Xe = pressure(n,V,T,a,b)
# print('{}'.format(vdWP_Xe))
# Check that you can use your function to plot vdW pressure vs volume for a tempera
ture of interest. For
# this, you could choose your analytical value of Tc if you wish.
ax = plt.axes()
ax.plot(V,vdWP_Xe)
Out[93]:
[<matplotlib.lines.Line2D at 0x7fd12f403150>]
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 9/11
10/26/2020 Lab1c_assignment
In [116]:
import numpy as np
import matplotlib.pyplot as plt
# Next, create a plot like the one in this markdown cell, but for the gas Xe. It sh
ould include few
# isotherms with temperatures below the critical temperature and a few with tempera
tures above the critical
# temperature. A nice way to do this is to create a loop that will plot the vdW iso
therm where each iteration
# of the loop uses a different temperature. I used 11 tempeartures in my plot, abov
e, for N2, over the range
# 110-210 K. I used a log-x plot where the x-axis is plotted logarithmically but th
e y-axis is plotted linearly,
# using the function np.semilogx, rather than our usual linear/linear plots created
using np.plot, but this
# isn't essential.
V = np.linspace(.000075,.0005,1000)
R = 8.31
a = 4.192e-1 # Pa m^6 mol^-2
b = 0.05156e-3 # m^3 mol^-1
def pressure(V,T,a,b):
return n*R*T/(V-n*b) - (a*n**2)/(V**2)
ax = plt.axes()
# for i in range(240,350,10):
# ax.plot(pressure(V,i,a,b))
for i in range(240,350,10):
ax.semilogx(V,pressure(V,i,a,b))
plt.ylim(-1e6,1.75e7)
plt.xlim(.000075,.0004)
plt.xlabel('Volume (m^3)')
plt.ylabel('Pressure (Pa)')
plt.title('Pressure vs. Volume')
# Examine your plot to find the temperature at which the wiggles seem to disappear.
Print out the following statement.
# "My analytical result predicted Tc = XXX K and inspecting a plot of the vdW isoth
erms provided an approximate value
# of Tc = YYY K."
# analytical result:
Tca = 8*a / (27*b*R)
print('My analytical result predicted Tc = {:.3f} K and inspecting a plot of the vd
W isotherms provided an approximate value of Tc = 290 K.'.format(Tca))
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 10/11
10/26/2020 Lab1c_assignment
In [ ]:
https://rttl.axdd.s.uw.edu/2020-autumn-chem-145-a/user/eymiller/lab? 11/11