我试图找出为什么我的代码没有正确迭代这些值。
我在这里定义了这个函数:
"""
=================================================================
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))
然后我尝试绘制近似解与真实解决方案,并使用以下代码打印错误:
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()
我得到了这些价值观:
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 ]
当我应该得到负值,并且误差要小得多。有谁知道我哪里出错了?
答案 0 :(得分:0)
你的括号错了。解决方案是y(t) = -3 + 2(1+e^-2t)^-1
,但在包含解决方案的函数中,它显示为(-3.0 + 2.0*(1.0 + np.exp((-2.0*t))**-1.0))
。在后者中,您只将^-1
应用于指数而不是总和。因此,如果您将其更改为(-3.0 + 2.0*(1.0 + np.exp(-2.0*t))**-1.0)
,它应该可以正常工作。