简体   繁体   English

优化浮点计算

[英]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 . 必须使用float中间矩形方法 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. 您说您必须使用float ,所以我认为问题不在于舍入,而在于更精确地计算积分。

I also assume that simply increasing N is not an option. 我还假设仅增加N是不可行的。

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...). 有很多方法可以避免或补偿浮点舍入(MM的建议,使用Kahan求和,等等)。 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. 本书“数字食谱” (有多个版本,一个用于C)受到高度重视。 Haven't looked at it personally. 还没亲自看过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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