迭代法,绘图误差,PYTHON中点法,数值分析2

2024-09-24 02:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出为什么我的代码没有正确地迭代这些值。你知道吗

我在这里定义了函数:

    """ 
=================================================================
    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 ]

当我得到负值的时候,一个小得多的误差。有人知道我哪里出错了吗?你知道吗


Tags: ofexampledefnppltexactfnode
1条回答
网友
1楼 · 发布于 2024-09-24 02:15:16

你的括号错了。解决方案是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),它应该可以正常工作。你知道吗

相关问题 更多 >