I'm trying to figure out why my code is not iterating the values correctly.
I defined the function here:
"""
=================================================================
Example 4: IVP of ODE y' = -(y+1)(y+3)
with intial value y(0) = -2
Exact solution is y(t) = -3 + 2(1+e^-2t)^-1
from t in [0,2]
h = 0.2
Exercise 5.4 No. 3c on page 291
def exmp4_def_fn(tau,w):
return (-1.0*((w + 1.0)*(w + 3.0)))
def exmp4_sol(t):
return (-3.0 + 2.0*(1.0 + np.exp((-2.0*t))**-1.0))
Then I try to plot the approximated solution vs the true solution and print the error with this code:
N4 = 10
a4 = 0.0
b4 = 2.0
ya4 = -2.0
#defining function and true solution of function #4
def_fn4 = exmp_fn.exmp4_def_fn
sol4 = exmp_fn.exmp4_sol
#run Euler's method from ODE_Approx_methods for example #4
(t4, w4) = ODE_Approx_methods.euler(def_fn4, a4, b4, ya4, N4)
#Exact solutions for comparison of example #3
z4 = sol4(t4)
#plot comparison of exact solution w(t) and approximation y(t), example
4'
plt.figure(4)
print('Errors at time mesh points, Example #4: ')
print(np.abs(np.transpose(np.ravel(w4)-z4)))
plt.rcParams.update({'font.size': 20})
plt.plot(t4,z4, 'b-' , marker= 'o', linewidth=2)
plt.plot(t4,w4, 'c-', marker = '*', linewidth=2)
plt.xlabel('t4')
plt.ylabel('w(t4)')
plt.legend([' Exact Solution', 'Euler Approximation, Example #4'], loc
=
'lower right' )
plt.show()
Im getting these values:
print(w4):[-2. -1.8 -1.608 -1.4387328 -1.30173697
-1.19925122 -1.12749094 -1.07974536 -1.04911908 -1.02995398
-1.01815184]
print(z4):[ 1. 1.9836494 3.45108186 5.64023385
8.90606485 13.7781122 21.04635276 31.88929354 48.06506039
72.19646889 108.19630007]
print(np.abs(np.transpose(np.ravel(w4)-z4))):[ 3. 3.7836494
5.05908186 7.07896665 10.20780182
14.97736342 22.17384371 32.9690389 49.11417947 73.22642287
109.2144519 ]
When im supposed to get negative values, and a much much smaller error. anyone understand where i went wrong?