Python
Python
Laoshi: 赛欧拉
College of Science
Department mathematics
Question No 1
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from matplotlib.animation import FuncAnimation
# Initial guess
initial_guess = np.array([0, 0])
# Function contour
x_vals = np.linspace(-2, 2, 400)
y_vals = np.linspace(-1, 3, 400)
X, Y = np.meshgrid(x_vals, y_vals)
Z = f([X, Y])
contour = ax[0].contour(X, Y, Z, levels=np.logspace(-1, 3, 10), cmap='viridis')
contour = ax[1].contour(X, Y, Z, levels=np.logspace(-1, 3, 10), cmap='viridis')
import numpy as np
from scipy.optimize import minimize
# Number of atoms
n_atoms = 13
# Function to calculate the total potential energy for all pairs of atoms
def total_potential(positions):
energy = 0
for i in range(n_atoms): # Corrected the variable name from I to i
for j in range(i + 1, n_atoms): # Corrected the variable name from J to j
r = np.linalg.norm(positions[i] - positions[j])
energy += potential_pair(r, 2) # You can adjust the value of ‘s’ as needed
return energy
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
# Define a range of x values for plotting the original function and the interpolation
x_values = np.linspace(0, 3*np.pi/2, 1000)
y_original = f(x_values)
y_interpolated = interpolated_function(x_values)
import numpy as np
import matplotlib.pyplot as plt
# Generate x values for plotting the true function and the fitted polynomial
x_values = np.linspace(-1, 1, 1000)
y_true = true_function(x_values)
y_fit = np.polyval(coefficients, x_values)
# Plot the true function, noisy data points, and the fitted polynomial
plt.plot(x_values, y_true, label='True Function')
plt.scatter(x_data, y_data, color='red', label='Noisy Data Points')
plt.plot(x_values, y_fit, label=f'Polynomial Fit (Degree {degree})', linestyle='dashed')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()
Question 5 integration
import numpy as np
from scipy.integrate import dblquad
def x_upper_limit(y):
return y
# Initial condition
y0 = 1
# Time points for integration
x = np.linspace(2, 10, 100) # Adjust the time range as needed
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Initial conditions
u0 = [2, 0]