Home > Net >  Am I implementing Euler's Method correctly in C ?
Am I implementing Euler's Method correctly in C ?

Time:10-26

I was asked to write a C or C program to solve the given differential equation

This must be achieved numerically using Euler method. The user should be able to enter the velocity(v), the initial value of x(0) and the final Time (T) at the beginning of the program.It should also plot the numerical solution for times 0 <t < T.

I felt like I got the program running fine, but I am having trouble implementing the Euler method correctly in the respect to the equation. Here is the program I have created. Any feedback/advise would be greatly be appreciated. Let me know if you require more information.

#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
using namespace std;
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include <array>
#include "gnuplot.cxx"

int main()
{
    //establishing  values
    double v, x0, T, dt, number_steps;
    const int max_number_steps = 100000;
    int i=0;
    
    //establishing numverical arrays
    double value_t [max_number_steps];
    double approx_x [max_number_steps];
 
   //Allow users to input variables
    cout<<"Enter Initial Condition"<< endl;
    cout<<"Velocity(v) = ";
    cin>> v;
    cout<<"x0 = ";
    cin >> x0;
    cout<<"Final time(T) = ";
    cin >> T;   
    cout << "number steps = ";
    cin >> number_steps;
    
    //Establishing stepside and assigning arrays
    dt = T/number_steps;
    value_t[0]= 0.0;
    approx_x[0] = x0;

    //for loop which should implement Euler's Method 
    for ( i= 0; i < number_steps; i  )
    {
        value_t [i 1] = dt*(i 1);
        approx_x[i 1] = approx_x[i 1]   dt*v;

    }
    
    //Graph the plot via gnuplot
     gnuplot_one_function("Velocity", "linespoints", "Time(t)", "Position(x)", value_t, approx_x, number_steps);

    return 0;
}

CodePudding user response:

Apart from the clean-code-related issues, you have a bug here:

approx_x[i 1] = approx_x[i 1]   dt*v;

Euler method calculates x_{i 1}th element from x_{i}th element, and a right hand side of the differential equation multiplied by step so:

approx_x[i 1] = approx_x[i]   dt*v;  // where approx_x[0] = x_0;

CodePudding user response:

You have a fundamental error with the Euler method concept.


my_aprox[i   1]  = my_aprox[i]   dt*v

Remember, to calculate a new approximation you have to have "a priori" the initial value which, with the next approximation will be the next initial value an so.

  • Related