Assignment 7
Assignment 7
March 6, 2025
n = 1
while n < max_iter:
h = (b - a) / (2**n)
# Compute the trapezoidal rule estimate with 2^n subintervals.
sum_f = sum(f(a + (2 * k - 1) * h) for k in range(1, 2**(n-1) + 1))
Rn0 = 0.5 * R[n-1][0] + h * sum_f
R.append([Rn0])
# Apply Richardson extrapolation to improve the estimate.
for m in range(1, n + 1):
factor = 4**m
Rnm = R[n][m-1] + (R[n][m-1] - R[n-1][m-1]) / (factor - 1)
R[n].append(Rnm)
# Check if the last two estimates have converged.
if abs(R[n][n] - R[n-1][n-1]) < tol:
return R[n][n]
n += 1
# If max_iter is reached, return the best estimate.
return R[n-1][n-1]
1
# integral2 = romberg_integration(f, singularity + epsilon, b)
integral = 0
for i in range(nx + 1):
for j in range(ny + 1):
weight = 1
if i in (0, nx): weight *= 0.5
if j in (0, ny): weight *= 0.5
integral += weight * f(x[i], y[j])
return integral * hx * hy
2
prev_integral = trapezoidal_2D(nx, ny)
for _ in range(max_iter):
nx *= 2
ny *= 2
new_integral = trapezoidal_2D(nx, ny)
prev_integral = new_integral
# Generate x values
x_values = np.linspace(-4, 4, 400)
for n in range(4):
y_values = [psi(n, x) for x in x_values]
plt.plot(x_values, y_values, label=f"n = {n}")
3
plt.title("Quantum Harmonic Oscillator Wavefunctions")
plt.xlabel("x")
plt.ylabel(r"$\psi_n(x)$")
plt.legend()
plt.grid()
plt.show()
4
plt.grid()
plt.legend()
plt.show()
epsilon = 1e-15
delta = 1.0
while delta > epsilon:
p0 = np.ones(N)
p1 = np.copy(x)
for k in range(1, N):
p0, p1 = p1, ((2*k+1)*x*p1 - k*p0)/(k+1)
dp = (N+1)*(p0 - x*p1)/(1-x*x)
dx = p1/dp
x -= dx
5
delta = max(abs(dx))
w = 2*(N+1)**2/(N**2 * (1-x*x)*dp*dp)
return x, w
# Compute �x²� using Gaussian quadrature with 100 points and the mapping x =␣
↪tan((�/2)*t)
def compute_x2(n):
N = 100 # number of Gaussian quadrature points
t, w = gaussxwab(N, -1, 1) # integration over t in [-1,1]
# Transformation: x = tan((�/2)*t)
x = np.tan((pi/2)*t)
# Jacobian: dx/dt = (�/2)*sec^2((�/2)*t)
dxdt = (pi/2) * (1/np.cos((pi/2)*t)**2)
return integral
[ ]: