• C

Integration in C

  I want to integrate a function. can anybody suggest me how to improve the code..

for( x = x1; x <= x2; x += 0.01)                  
            f1 = some function(x)
            res += f1/10000.0;

IS this right??
Can u plzz show me the code to do integration using any std rules..
Who is Participating?
van_dyConnect With a Mentor Commented:
Hi Suma,
       You can use the any of the availiable numerical integration
techniques to calculate the definite integral of a function. Have a look at


the techniques range from fairly complex Newton-cote's method
to relatively simple trapezoidal rule.  You  need to be more specific
about the algorithm you want to implement.
As a simple implementation, consider dividing your integration space into
N equal sized intervals, and assume that the intervals are small enough
so that the function value in the i-th interval can be approximated as f((X[i] + fX[i+1])/2) throughout;
then a rough integration function can be;


double function(X)
              double X;
        // The body of the function you are integrating over [X1, X2];

double integrator(X1,  X2)
               double X1, X2
         double Increment = (X2 - X1)/ N;
         double  X = X;
          double Result = 0.0;

          for (; X < X2; X += Increment)
                   Result +=  function(X + Increment/2);

            return Result;

Similarily you can implement any of the techniques once you have read about them.
hi Suma,

What exactly do you mean by "integrate a function" ? pls explain

Well well, in the integrator(X1, X2), second line reads:

            double X = X1;
             double Result =  0.0;
and the last line would be

         return Result * Increment;

:D, tooo much hurry;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.