There are two problems with your code:
- The analytical solution is incorrect
- You increment x inside the for loop. Don't. The for loop does this automatically.
Here is a corrected version:
a = 0.2;
y0 = 1;
x0 = 1;
xn = 1.5;
h = 0.1;
dy = @(x,y)a*x*y;
f = @(x) y0*exp(a/2*(x.^2-1));
y = y0;
fprintf ('x \t \t y (euler)\t y(analytical) \n')
fprintf ('%f \t %f\t %f\n' ,x0,y,f(x0));
for x = x0+h : h: xn
y = y + dy(x,y)*h;
fprintf ('%f \t %f\t %f\n' ,x,y,f(x));
end
Choose a smaller step length h to for better accuracy. Alternatively try a higher order method like Runge-Kutta.
Best Answer
If you define
you can work with the code from above.
Best wishes
Torsten.