python中euler方法逼近正弦波

2024-09-30 01:24:13 发布

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

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

使用以下算法:

  1. 定义f(t,y)

  2. 输入t0和y0 .

  3. 输入步长h和步数n . 在
  4. 对于从1到n的j do:

    4a.m=f(t0,y0)

    4b.y1=y0+h*m

    4c.t1=t0+h

    4d.打印t1和y1

    4e.t0=t1

    4f.y0=y1

    4g.结束

在我的例子中,我是近似函数sin(A),所以我的函数是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

我一定是在做一些很蠢的事,但我想不通。在

感谢任何帮助。在


Tags: 函数timepltsincosstepsnumt1

热门问题