Hi I'm trying to use euler method in python to plot a sin wave function sin(A).
Using the following algorithm:
define f(t,y)
input t0 and y0 .
for j from 1 to n do:
4a. m=f(t0,y0)
4b. y1=y0+h∗m
4c. t1=t0+h
4d. Print t1 and y1
4e. t0=t1
4f. y0=y1
4g. end
in my case I am approximating the function sin(A) so my function is the deriviative of sin(A) which is cos(A).
I've implemented it in the code as below
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')
It seems like no matter what i do to the step size the derivative cos(A) heads towards zero but never gets to be negative. It has to be negative to make the sine wave function go down. so it can oscillate. My erroneuos results are pictures here:
I must be doing something really dumb, but i can't figure it out.
Any help is appreciated.
You are solving the ODE
y'(t) = cos(y(t))
which has an attracting stable point at y=pi/2
which you reach for t=10
for all graphical purposes, after that the solution is constant. As you got in your graph.
You need either a system
x' = -y
y' = x
or on a limited interval
y' = sqrt(1-y^2)
Or in a simple integration
y'(t) = cos(t).