Search code examples
c++loopsfor-loopapproximation

How to write a nested for-loop


I'm running a program that preforms a Euler Approximation of an Ordinary Differential Equation. The smaller the step size that is chosen, the more accurate the approximation is. I can get it to work for a set step size using this code:

#include <iostream>
using std::cout;

double f (double x, double t)
 {
     return t*x*x-t;
 }

 int main()
 {
     double x=0.0,t=0.0,t1=2.0;
     int n=20;
     double h = (t1-t) / double(n);

 // ----- EULERS METHOD

     for (int i=0; i<n; i++)
     {
         x += h*f(x,t);
         t += h;
     }

     cout << h << " " << x << "\n";

 }

So this code runs a Eulers approximation for n=20 which corresponds to a step size of 0.1 and outputs the step size along with the approximation for x(2). I want top know how to loop this code (for different values of n) so that it outputs this followed by increasingly smaller step sizes with corresponding approximations. i.e an output something like this:

0.1   -0.972125
0.01  -0.964762
0.001 -0.9641

etc.

So I tried a for-loop inside a for-loop but its giving me a weird output of extreme values.

#include <iostream>
using std::cout;

double f (double x, double t)
 {
     return t*x*x-t;
 }

int main()
 {
     double x=0.0,t=0.0,t1=2.0;

     for (int n=20;n<40;n++)
     {
         double h = (t1-t)/n;
         for (int i=0;i<n;i++)
         {
             x += h*f(x,t);
             t += h;
         }
         cout << h << " " << x << "\n";

     }

 }

Solution

  • If I understand correctly, you want to execute that first piece of code inside your main function for different values of n. Then your problem is with the variables x, t and t1, which are set once before the loop and never reset. You want them inside your outer loop:

    #include <iostream>
    
    using std::cout;
    
    double f( double x, double t )
    {
        return t * x * x - t;
    }
    
    int main()
    {
        for ( int n = 20; n < 40; n++ )
        {
            double x = 0.0, t = 0.0, t1 = 2.0;
            double h = ( t1 - t ) / n;
            for ( int i = 0; i < n; i++ )
            {
                x += h * f( x, t );
                t += h;
            }
            cout << h << " " << x << "\n";
        }
    }
    

    Using a function for this, makes it clearer:

    #include <iostream>
    
    using std::cout;
    
    double f( double x, double t )
    {
        return t * x * x - t;
    }
    
    void eulers( const int n )
    {
        double x = 0.0, t = 0.0, t1 = 2.0;
        double h = ( t1 - t ) / n;
        for ( int i = 0; i < n; i++ )
        {       
            x += h * f( x, t ); 
            t += h; 
        }       
        cout << h << " " << x << "\n";
    }
    
    int main()
    {
        for ( int n = 20; n < 40; n++ )
        {
            eulers( n );
        }
    }
    

    Hope this helps.