Sorry, but your code is wrong (so is your exact solution.) Why? Look at what you wrote.
dydt = 4*exp(0.8*t) - 0.5*y;
So dydt is a VECTOR. t and y are vectors. However, y is a vector with first element 2, and EVERY other element 0.
y(i+1)= y(i)+ h * dydt(i);
How do you use dydt? Remember, it was fixed before the loop. Those vector elements don't change. You never update dydt when y changes. Therefore you are not solving the problem you think you are solving. You need to update dydt as a function, that changes as both y and t vary. If you don't, well then you get arbitrary garbage as a result - what you got, in fact. That is, you CANNOT create dydt in advance as avector.
So first, let me check your claim as to the solution.
true_sol = dsolve(diff(y,t,1) == 4*exp(0.8*t) - 0.5*y(t),y(0) == 2)
true_sol =

Interestingly, that is also not the same as what you claim to be the solution. So exact_sol is also incorrect.
simplify(true_sol - (4/1.3)*(exp(0.8*t)-exp(-0.5*t))+2*exp(-0.5*t))
ans =

I'm not sure what you screwed up in the solve, but your "exact_sol" is not. Not exact, that is. And since I don't see your code, I can only guess what you did wrong on paper. I won't try to do that.
Now let me implement Euler's method. I'll still use your code as a template, but mine will be correct. :)
dydt = @(y_i,t_i) 4*exp(0.8*t_i) - 0.5*y_i;
y(i+1)= y(i)+ h * dydt(y(i),t(i));
fplot(true_sol,[0,4],'r');
You can see the two curves as I plotted them are now almost on top of each other. A little larger value of h would have been good perhaps to show off the difference more. But Euler actually did pertty well here.
0 Comments
Sign in to comment.