user2024645
user2024645

Reputation: 21

numerical integration with c

I have to do numerical integration for a set of data points from a text file.

my data points look like

0.5   0.479425539
1     0.841470985
1.5   0.997494987
2     0.909297427
2.5   0.598472144
3     0.141120008
3.5   -0.350783228
4     -0.756802495
4.5   -0.977530118
5     -0.958924275  

my attempt is

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <conio.h>

double trapezoidalRule (double size, double *x, double *y)
{
    double sum = 0.0,increment;
    int k;
    for (k=1; k<size; k++)
    {
        increment = 0.5 * (x[k]-x[k-1]) * (y[k]+y[k-1]);
        sum += increment;
    }
    return sum;
    _getch();
}
int main ( int argc, char * argv[])
{
    char*  fileName = argc > 1 ? argv[1] : "C:\\Users\\g\\Desktop\\test.txt";
    FILE*  inputFile = fopen (fileName, "r");
    int  k;
    double size,*x, *y;
    double integral;
    if ( inputFile ==NULL)
    {
        fprintf (stderr, "Open failed for %s\n", fileName);
        exit(666); 
    }
    fscanf (inputFile, "%d", &size);
    printf (" Number of points: %d\n", size);

    x = (double *) calloc (size, sizeof(*x));
    y = (double *) calloc (size, sizeof(*y));

    for (k=0; k< size; k++)
        fscanf (inputFile, "%lg%lg" , x+k, y+k);
    integral = trapezoidalRule (size, x, y);
    printf ("Integral:", "\n", integral);
    printf ("\n");
    //printf ("check: ","\n", x[size-1], log(x[size-1]) );
    _getch();
}

but I am not getting the required output... I cant figure whats wrong... It shud compute the integral value, but its not... also the no of points is wrong...its just taking the first number, not counting the no of points... pls help...

Upvotes: 1

Views: 10231

Answers (2)

Dr_Sam
Dr_Sam

Reputation: 1878

I think that you are not that far from the solution. The formula at least looks fine.

Maybe the biggest mistake that you have in your code is that you are missing, in your data, the number of points to read. So you code probably reads "0.5" as the number of points. Then, the loop on k just goes for k=0 (then k=1>0.5), that probably why you have only one point. To make it work, I did the following changes:

  • Add the number of points at the beginning of your data file.
  • Change the type of size for int size
  • Print the value of the integral printf ("Integral: %lg \n", integral);

That made it work for me.

(Big edit since it has been retaged as C instead of C++)

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

You should not be reading a double value using %d instead use the format specifier %lf. Also I do not understand why size is double. It seems it can only be a non-negative integer so probably unsigned will do best here.

Upvotes: 0

Related Questions