使用python中的欧拉方法逼近正弦波

时间:2019-02-06 20:12:11

标签: python numpy ode approximation

嗨,我正在尝试在python中使用euler方法绘制正弦波函数sin(A)。

使用以下算法:

  1. 定义f(t,y)

  2. 输入t0和y0

  3. 输入步长,h和步数,n 。
  4. 对于从1到n的j做:

    4a。 m = f(t0,y0)

    4b。 y1 = y0 + h ∗ m

    4c。 t1 = t0 + h

    4d。打印t1和y1

    4e。 t0 = t1

    4f。 y0 = y1

    4克。结束

在我的情况下,我近似函数sin(A),所以我的函数是sin(A)的导数,即cos(A)。

我已经在下面的代码中实现了它

def dSindt(A): 
    dSindt = cos(A) ;
    return dSindt; 



%matplotlib inline
import matplotlib.pyplot as plt

A0 = 0 
t0 = 0; 
tf = 3600
del_t = .1; 
num_steps = int((tf - t0)/del_t); 
A_mesh = [0]*(num_steps + 1);
time_mesh = [0]*(num_steps + 1); 

A_mesh[0] = A0;
time_mesh[0] = t0;

for i in range(num_steps):
    A_mesh[i+1] = A_mesh[i] + dTindt(A_mesh[i])*del_t 
    time_mesh[i+1] = time_mesh[i] + del_t; 

plt.plot(time_mesh,A_mesh,color='b');
plt.title('Approx. Sin Wave');
plt.xlabel('Time (min)');
plt.ylabel('A')

似乎无论我对步长做什么,导数cos(A)都趋于零,但永远不会为负。使正弦波函数下降必须为负。所以它会振荡。我的错误结果是以下图片:enter image description here

我一定在做些愚蠢的事,但我不知道。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您正在解决ODE

y'(t) = cos(y(t))

y=pi/2有一个吸引人的稳定点,对于所有图形目的,您都会达到t=10,然后解决方案是恒定的。当您进入图表时。

您需要一个系统

x' = -y
y' =  x

或在有限的时间间隔

y' = sqrt(1-y^2)

或者通过简单的集成方式

y'(t) = cos(t).