简体   繁体   English

在 python 中使用欧拉法求微分的解

[英]Finding a solution of a differential using the Euler method in python

I am trying to find the solution of a differential equation at a point using the Euler method but I am getting a wrong answer.我正在尝试使用欧拉方法在某个点找到微分方程的解,但我得到了错误的答案。 See my code below:请参阅下面的代码:

#Intial conditions
x0, y0 = 0, 1

h = 0.1 #step size
x_end = 1.0 #the value of x for which we want to know y

##The ODE function
def f(x,y):
    return 1/(1 + x*x)

x_arr = np.arange(x0, x_end + h, h)
y_arr = np.zeros(x_arr.shape)

y_arr[0] = y0

for i, x in enumerate(x_arr[:-1]):
    y_arr[i+1] = y_arr[i] + h*f(x, y_arr[i])

print("x array", x_arr)
print("y array", y_arr)

Output: Output:

x array [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]

y array [1.         1.1        1.1990099  1.29516375 1.38690687 1.47311376
 1.55311376 1.62664317 1.69375727 1.75473288 1.8099815 ]

According to the python solution, y = 1.8099815 at x = 1.0 but I should be getting y = 1.85998149722679 at x = 1.0.根据 python 解决方案,在 x = 1.0 时 y = 1.8099815 但我应该在 x = 1.0 时得到 y = 1.85998149722679。

Am I doing something wrong?难道我做错了什么? I am sure I am applying the Euler method correctly.我确信我正确地应用了欧拉方法。

No, your result is correct for the step size.不,您的结果对于步长是正确的。 You can get this result of 10 steps shorter with您可以通过以下方式获得缩短 10 步的结果

x = np.arange(0,1-1e-6,0.1); 
print(0.1*len(x), 1+0.1*sum(1/(1+x*x)))
## >>> 1.0    1.8099814972267896

The other value is for the next step at x=1.1另一个值用于x=1.1处的下一步

x = np.arange(0,1.1-1e-6,0.1); 
print(0.1*len(x), 1+0.1*sum(1/(1+x*x)))
## >>> 1.1    1.8599814972267898

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM