简体   繁体   中英

Optimize floating-point calculations

I have a task to make the following function as precise (the speed is not the aim) as possible. I have to use float and the method of middle rectangles . Could you suggest something? Actually, I think, it's all about minimization of float rounding errors. That's what I've done:

typedef float T;

T integrate(T left, T right, long N, T (*func)(T)) {
    long i = 0;
    T result = 0.0;
    T interval = right - left;
    for(i = 0; i < N; i++) {
        result += func(left + interval * (i + 0.5) / N) * interval / N;
    }
    return result;
}

I have a task to make the following function as precise as possible

You say that you have to use float , so I assume the question isn't about rounding, but rather about computing the integral more accurately.

I also assume that simply increasing N is not an option.

Instead of using the mid-point rule, my suggestion is to consider using a higher-order quadrature rule (trapezoid, Simpson's etc) .

There are lots of ways you could avoid or compensate for floating-point rounding (MM's suggestion, using Kahan summation, etc...). However, there's no reason to do so, because the rounding errors are absolutely dwarfed by the error of the integration scheme; you won't get a more accurate integral, you'll get a more accurate approximation of the incorrect result computed by the midpoint rule. Any such effort is entirely wasted except in extremely specialized circumstances.

Try this:

{
   long i = 0;
   T result = 0.0;
   T interval = right - left;
   for(i = 0; i < N; i++) {
       result += func(left + interval * (i + 0.5) / N);
   }
   return result * interval / N;
}

If you want to compute an integral precisely, go read up on integration schemes. Some home-knit routine won't give any kind of precision

The book "Numerical recipes" (there are several versions, one for C) is highly regarded. Haven't looked at it personally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM