# Category: Differential Equations
# Name: Euler's Method graphs for the exponential

# You can play around with different 
# differential equations, the equation is dy/dx = g(x,y)
function g(x,y)=y;
LinePlotWindow=[-0.2,4,0,e^4+0.2];

LinePlotDrawLegends=false;
LinePlotClear();
PlotWindowPresent(); # Make sure the window is raised

LinePlotDrawPoints(0,1,"thickness",10,"color","red");

AskButtons("The initial point (0,1)","Next");

# h is step size, x0, y0 are the initial conditions
h=1;
x0=0;
y0=1;

xx=[x0];yy=[y0];
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = yy@(j-1)+g(xx@(j-1),yy@(j-1))*h;
);
LinePlotDrawLine ([xx',yy'],"color","darkgreen");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("Step size h = 1","Next");

h=(1/2);
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = yy@(j-1)+g(xx@(j-1),yy@(j-1))*h
);
LinePlotDrawLine ([xx',yy'],"color","blue");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("h = 0.5 = 1/2","Next");

h=(1/4);
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = yy@(j-1)+g(xx@(j-1),yy@(j-1))*h
);
LinePlotDrawLine ([xx',yy'],"color","orange");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("h = 0.25 = 1/4","Next");

h=(1/8);
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = yy@(j-1)+g(xx@(j-1),yy@(j-1))*h
);
LinePlotDrawLine ([xx',yy'],"color","brown");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("h = 0.125 = 1/8","Next");

h=(1/16);
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = yy@(j-1)+g(xx@(j-1),yy@(j-1))*h
);
LinePlotDrawLine ([xx',yy'],"color","darkgreen");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("h = 0.0625 = 1/16","Next");

h=(1/32);
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = yy@(j-1)+g(xx@(j-1),yy@(j-1))*h
);
LinePlotDrawLine ([xx',yy'],"color","blue");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("h=0.03125=1/32","Next");

# The real solution
for j=2 to (4/h)+1 do (
  xx@(j) = xx@(j-1)+h;
  yy@(j) = e^(xx@(j))
);
LinePlotDrawLine ([xx',yy'],"color","red");
PlotWindowPresent(); # Make sure the window is raised
AskButtons("The real solution","End");
