Here is an example of how to use NumPy to solve a second-order ODE using finite differences:
First, we can import NumPy and set up the grid of x-values:
import numpy as np
# Set up the grid of x-values
N = 10 # Number of points
x0 = 0 # Starting x-value
xN = 1 # End x-value
h = (xN - x0)/(N - 1) # Distance between points
x = np.linspace(x0, xN, N) # Array of x-values
Next, we can define the function $y(x)$ and its second derivative $y”(x)$:
def y(x):
return x**2 # y(x) = x^2
def y_2prime(x):
return 2 # y''(x) = 2
Note that in this example, we are using a function that has a known second derivative. In general, you would need to approximate the second derivative using finite differences as shown in the previous example.
Now we can solve for y at each point on the grid using the ODE:
# Initialize array to store y-values
y_values = np.zeros(N)
# Solve for y at each point
for i in range(N):
y_values[i] = -y_2prime(x[i]) # Substitute y''(x) into the ODE
Finally, we can plot the results using Matplotlib:
import matplotlib.pyplot as plt
# Plot the results
plt.plot(x, y_values, label='Numerical solution')
plt.plot(x, y(x), label='Exact solution')
plt.legend()
plt.show()
This should produce a plot showing the numerical solution (in blue) and the exact solution (in orange) on the same graph.
Here is the complete code that combines the steps I described above:
import numpy as np
import matplotlib.pyplot as plt
# Set up the grid of x-values
N = 10 # Number of points
x0 = 0 # Starting x-value
xN = 1 # End x-value
h = (xN - x0)/(N - 1) # Distance between points
x = np.linspace(x0, xN, N) # Array of x-values
def y(x):
return x**2 # y(x) = x^2
def y_2prime(x):
return 2 # y''(x) = 2
# Initialize array to store y-values
y_values = np.zeros(N)
# Solve for y at each point
for i in range(N):
y_values[i] = -y_2prime(x[i]) # Substitute y''(x) into the ODE
# Plot the results
plt.plot(x, y_values, label='Numerical solution')
plt.plot(x, y(x), label='Exact solution')
plt.legend()
plt.show()
Leave a Reply