Implement Euler’s method to solve the differential equation \(y'=-ty\) with initial condition \(y(0)=1\text{.}\) Plot the result on the interval \([0, 3]\) and compare it with the exact solution, which is \(y(t) = \exp(-t^2/2)\text{.}\) Try different step sizes: 0.3, 0.1, 0.01.
Answer.
f = @(t, y) -t*y; % or without -
h = 0.3; % or 0.1, 0.01
t = 0:h:3;
y0 = 1;
y = y0*ones(size(t));
for k = 1:numel(t)-1
y(k+1) = y(k) + h*f(t(k), y(k));
end
exact = exp(-t.^2 /2); % or without -
plot(t, y, t, exact)
legend('Euler', 'exact')
