Question : Use Python ODEINT to solve y’= x+y, y(0) = 1/2? Find absolute error if exact solution to the initial-value problem is y(x) = 3e^x/2-x-1. Plot the graphs of approximate and analytical solutions
Answer :
To solve initial-value problem
\[y’=x+y,y(0)=\frac{1}{2}\]
# Program using Python ODEINT to solve y’= x+y, y(0) = 1/2.
#Find absolute error if exact solution to the initial-value problem is y(x) = e^x/2-x-1.
# Plot the graphs of approximate and analytical solutions.
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import math
def dydt(y,x):
dydx = y+x # dy/dx = f(x,y)
return dydx
def exact(x):
return np.exp(x)/2-x-1
y0 = 0.5 # y(t0)=y0
x = np.linspace(0,1,10) # time points
y = sp.integrate.odeint(dydx,y0,x) # solution of differential equation
y = np.squeeze(np.asarray(y))
print(“x_n = “,x)
print(“y_n = “, y)
exactSol=exact(x)
print(“exactSol = “,exactSol)
Absolute_Error = np.abs(y-exactSol)
print(“Absolute_Error = “, Absolute_Error)
# ploting data
plt.plot(x,y,’r’)
plt.plot(t,exactSol,’g’)
plt.xlabel(‘x_n’)
plt.ylabel(‘y_n’)
plt.legend(“ye”)
plt.show()
Output:
x_n = [0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556 0.66666667 0.77777778 0.88888889 1. ] y_n = [0.5 0.56516748 0.65105108 0.76008529 0.89499079 1.05880794 1.25493444 1.48716714 1.75974932 2.07742278] exactSol = [0.5 0.56516749 0.65105108 0.7600853 0.8949908 1.05880794 1.25493439 1.48716712 1.75974929 2.07742274] Absolute_Error = [0.00000000e+00 1.30354476e-08 5.78513348e-09 1.00431969e-08 8.53063498e-09 4.79281970e-09 4.64786141e-08 1.97178553e-08 2.95029750e-08 3.56522438e-08]
