在python中使用matplotlib绘制欧拉近似和解析近似,产生意外输出

fiei3ece  于 2023-03-19  发布在  Python
关注(0)|答案(1)|浏览(149)

我试图画出微分方程dy/dx = x + y/5的欧拉近似和解析解,其中y(0)= -3

  1. import math
  2. import matplotlib.pyplot as plt
  3. def euler_method(step_size):
  4. first_x = 0
  5. last_x = 5
  6. h = step_size
  7. n = int((last_x-first_x) / h)
  8. x=0
  9. y=-3
  10. dy = lambda x,y: x + (y/5)
  11. f = lambda x,y: math.exp(x+(y/5))
  12. x_values = []
  13. euler_values= []
  14. analytical_values = []
  15. for i in range(1, n+1):
  16. x_values.append(x)
  17. euler_values.append(y)
  18. analytical_values.append(f(x,y))
  19. y = y + dy(x, y) * h
  20. x = x + h
  21. x_values.append(x); euler_values.append(y); analytical_values.append(f(x,y))
  22. plt.plot(x_values, euler_values, 'ro', x_values, analytical_values)
  23. plt.legend(['Euler values','Analytical values'])
  24. plt.show()
  25. euler_method(1)

我的输出如下:

这显然是不正确的,但我不知道为什么会发生这种情况,也不知道我必须做出什么改变来解决这个问题。

gudnpqoy

gudnpqoy1#

Wolfram Alpha为您的问题提供this analytical solution。您的问题在我看来不正确。与Stephen Wolfram的观点不一致。
我更正了你的代码。现在可以正常工作了:

  1. import math
  2. import matplotlib.pyplot as plt
  3. # see https://stackoverflow.com/questions/75751065/plotting-euler-approximation-and-analytical-approximation-using-matplotlib-in-py
  4. # Analytical solution: https://www.wolframalpha.com/input?i=22+e%5E%28x%2F5%29+-+5+%285+%2B+x%29&assumption=%22ClashPrefs%22+-%3E+%7B%22Math%22%7D
  5. def euler_method(step_size):
  6. first_x = 0
  7. last_x = 5
  8. h = step_size
  9. n = int((last_x - first_x) / h)
  10. x = 0
  11. y = -3
  12. dy = lambda x, y: x + (y / 5)
  13. f = lambda x, y: 22.0 * math.exp(x/5.0) - 5.0 * (5.0 + x)
  14. x_values = []
  15. euler_values = []
  16. analytical_values = []
  17. for i in range(1, n + 1):
  18. x_values.append(x)
  19. euler_values.append(y)
  20. analytical_values.append(f(x, y))
  21. y = y + dy(x, y) * h
  22. x = x + h
  23. x_values.append(x)
  24. euler_values.append(y)
  25. analytical_values.append(f(x, y))
  26. plt.plot(x_values, euler_values, 'ro', x_values, analytical_values)
  27. plt.legend(['Euler values', 'Analytical values'])
  28. plt.show()
  29. if __name__ == '__main__':
  30. euler_method(0.01)

下面是它生成的图:

展开查看全部

相关问题