How would I perform numeric integration?
This is a discussion on perform numeric integration within the C Programming forums, part of the General Programming Boards category; How would I perform numeric integration?...
How would I perform numeric integration?
How indeed.
Quzah.
Hope is the first step on the road to disappointment.
Read this (the whole thing, you need it): http://www.catb.org/~esr/faqs/smart-questions.html
If you understand what you're doing, you're not learning anything.
Do you want to know in general, or do you have a particular algorithm in mind?
One simple way is:
This is known as the 'midpoint method,' and is relatively well-known. There are many more sophisticated general numeric integration algorithms; this is about the simplest you'll find. Don't forget about floating point error.Code:#include <stdio.h> #include <math.h> double f(double x) { return 1.0 + exp(x); } /* Integrates f from a to b, using n intervals. */ double integrate(double (*f)(double), double a, double b, int n) { double interval_size = (b - a) / n; double x = a + interval_size * 0.5; double ret = 0.0; while (n--) { ret += (*f)(x); x += interval_size; } ret *= interval_size; return ret; } int main(void) { int i; puts("Approximations of the area underneath 1+e^x from 0 to 1:"); for (i = 1; i <= 20; ++i) { printf("%d intervals: %f\n", i, integrate(&f, 0.0, 1.0, i)); } return 0; }
For some popular functions, there exist specialized formulas that approximate the integral extremely well. For example, the normal curve has a whole slew of specialized formulas that are much more efficient than naive integration. So you might want to look around for those if you have a peculiar function in mind.
Last edited by Rashakil Fol; 10-17-2005 at 05:44 PM.
Thank-You!!
We have to use the trapezoidal rule with Richarson's expolation
>We have to use the trapezoidal rule with Richarson's expolation
That's nice. And what was your attempt at solving the problem?
My best code is written with the delete key.