有一个首选的方法来命令浮点操作数? [英] Is there a preferred way to order floating-point operands?

查看:120
本文介绍了有一个首选的方法来命令浮点操作数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个非常小的 float a (例如 a = 0.5 ),它输入下面的表达式:

  6000.f * a * a; 

操作数的顺序是否有所不同?是写得好吗?/ b>

  6000.f *(a * a); 

甚至

  float result = a * a; 
结果* = 6000.f;

我检查了经典每个计算机科学家应该知道的关于浮点算术的知识,但找不到任何东西。



在浮点运算中是否有一个最佳的方式来命令操作数?

这实际上取决于价值观和目标。例如,如果 a 非常小, a * a 可能为零,而 6000.0 * a * a (意味着(6000.0 * a)* a )仍然可以是非零。为了避免溢出和下溢,一般规则是应用联合定律首先在操作数日志符号相反的地方进行乘法运算,这意味着平方优先通常是最差的策略。另一方面,出于性能方面的原因,如果可以重新使用平方的值,则先平方可能是一个非常好的策略。您可能会遇到另一个问题,如果您的数字永远不会非常接近于零或无穷大,则可能比溢出/下溢问题的正确性更重要:某些乘法可能保证具有确切的答案,而另一些则涉及四舍五入。一般来说,通过减少发生舍入步骤的次数,您将得到最准确的结果。

Suppose I have a very small float a (for instance a=0.5) that enters the following expression:

6000.f * a * a;

Does the order of the operands make any difference? Is it better to write

6000.f * (a*a);

Or even

float result = a*a;
result *= 6000.f;

I've checked the classic What Every Computer Scientist Should Know About Floating-Point Arithmetic but couldn't find anything.

Is there an optimal way to order operands in a floating point operation?

解决方案

It really depends on the values and your goals. For instance if a is very small, a*a might be zero, whereas 6000.0*a*a (which means (6000.0*a)*a) could still be nonzero. For avoiding overflow and underflow, the general rule is to apply the associative law to first perform multiplications where the operands' logs have opposite sign, which means squaring first is generally a worst strategy. On the other hand, for performance reasons, squaring first might be a very good strategy if you can reuse the value of the square. You may encounter yet another issue, which could matter more for correctness than overflow/underflow issues if your numbers will never be very close to zero or infinity: certain multiplications may be guaranteed to have exact answers, while others involve rounding. In general you'll get the most accurate results by minimizing the number of rounding steps that happen.

这篇关于有一个首选的方法来命令浮点操作数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆