Euler's Method Solving $y' = f(t,y)$: Programming

44 Views Asked by At

I'm trying to compute the approximation solution for $$ y' = -2y + 2 - e^{-4t}: 0\le t\le5, y(0) = 1$$ but the answer that I get for $n = 100$ intervals is $-5.069$ which isn't right. What's the issue with my algorithm?

    valueA = 0;
    valueB = 5;
    double y0 = 1;
    double y1 = 0;
    double t = 0;
    valueN = 100;
    double valueM = 0;

    double functionOne = 0;
    double h = (valueB-valueA)/valueN;
    for (double i = 0; i <= 5.00; i+=h){
    valueM = ((-2*y0) + 2 - Math.exp(-4*t));

    y1 = y0 + (t * valueM);
    y0 = y1;
    t += h;


    }
    return y1;

First Ten Values:

  1. 1.0
  2. 0.959063462346101
  3. 0.9002187652733168
  4. 0.8478313902772178
  5. 0.8188330413428864
  6. 0.8174466603785826
  7. 0.8366204005777724
  8. 0.8646771827937695
  9. 0.8921768293608917
  10. 0.9148331832363752
  11. 0.9323323583816936
1

There are 1 best solutions below

2
On BEST ANSWER

With $t_{n+1} = t_n +\delta t$ your algorithm is essentially $y(t_{n+1}) = y(t_n)+\delta t y'(t_n)$.

I think the incriminated line is

  y1 = y0 + (t * valueM);

which should be

  y1 = y0 + (h * valueM);