Professional Documents
Culture Documents
[54]: #Q1:
#i)
import math
import matplotlib.pyplot as plt
import numpy as np
def H(n,x):
if(n<0):
return
if(n==0):
return 1
elif(n==1):
return 2*x
else:
return 2*x*H(n-1,x)-2*n*H(n-2,x)
def wavefunc(n,x):
f=1/(math.sqrt(2**(n)*fact(n)*math.sqrt(math.pi)))*np.exp(-x**2/2)*H(n,x)
return f
x=np.linspace(-4,+4,100)
for i in range(4):
plt.plot(x,wavefunc(i,x))
plt.show()
[17]: # ii)
x=np.linspace(-10,+10,200)
plt.plot(x,wavefunc(30,x))
plt.show()
1
[56]: #iii)
import numpy as np
leg=np.polynomial.legendre
def Gaussian(f,a,b,n):
g=lambda t: (b-a)/2*f((b-a)/2*t+(a+b)/2)
s=np.zeros(n+1,dtype=int)
s[n]=1
rt=leg.legroots(s)
der=leg.legder(s)
po=leg.Legendre(der)
w=(2/(1-rt**2)*(po(rt))**(-2))
I=0
I=np.dot(g(rt),w)
return I
f=lambda x:x**4-2*x+1
Gaussian(f,0,2,3)
[56]: 4.4
[90]: inf=36
def Uncertainty(n):
f=lambda x:x**2*(wavefunc(n,x))**2
return np.sqrt(Gaussian(f,-inf,inf,100))
print(Uncertainty(5))
f=lambda x:x**2*(wavefunc(n,x))**2
x=np.linspace(-inf,inf,100)
plt.plot(x,f(x))
plt.show()
2.259622260452205
def f(x):
"""Function to be differentiated."""
return 1 + (1 / 2) * np.tanh(2 * x)
2
def central_difference(f, x, h):
"""Calculates the derivative of f at x using the central difference formula.
,→"""
def analytic_derivative(f):
"""Calculates the analytic derivative of f."""
# return 2 * np.exp(4 * x) / (np.exp(4 * x) + 1) ** 2
return 1 / (np.cosh(2 * x) ** 2)
'''
Explanation of the error comparison:
The plot shows that the approximation error of the forward difference is smaller␣
,→than
3
plt.title("f(x) = 1 + (1/2)*tanh(2x)")
plt.legend()
plt.grid(True)
plt.show()
[ ]: