是否可以保证A / B的两倍始终等于A / B? [英] Can it guarantee the double value A/B is always equal to A/B?

查看:261
本文介绍了是否可以保证A / B的两倍始终等于A / B?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,由于double的精度有限,以下两个计算可能无法给出完全相同的值:



A / B / C和
A /(B * C)



我的问题是即使两个变量A& B,编译器能否保证每次A / B产生相同的值?



还是我应该在代码中询问,我们可以保证以下语句始终返回true: / p>

如果(A / B == A / B)

解决方案

对于编译器的行为保证,需要一些文档来指定行为。因此,答案取决于编程语言,并且,如果编程语言的规范不充分,则答案取决于所使用的特定编译器。



该问题无法确定任何特定的编程语言,更不用说任何特定的编译器了。某些编程语言具有指定其行为许多方面的标准,而某些编程语言则是非正式的并且不能清楚地记录行为。



在后一类中,Python表示浮动点行为是从其运行于任何平台上得出的。因此,我们不能轻易确定Python会做什么。



尚不完全清楚浮点行为。我打开了这个问题以寻求澄清,到目前为止我的解释是,该标准应被解释为要求实现使用其选择的一种格式来评估特定类型的浮点运算,但是编译器在历史上并未对此予以遵循。例如,较旧的GCC版本可以评估扩展精度的表达式,但会在不可预测的时间转换为名义精度。这可能会导致 A / B == A / B 评估为假(甚至不包括NaN,我假设在此处进行讨论)。



Java规范更具体地涉及浮点运算并指定符合IEEE 754,但指定了 FP-strict not FP-strict 模式,并且粗略地检查表明不是FP-strict模式可以允许 A / B 比较不等于 A / B


As we know, because of the limited precision of double, the following two calculation may not give the exact the same value :

A / B / C and A / ( B * C )

My question is even with the same two variable, A & B, can the compiler guarantee every time A / B yield the same value ?

Or I should ask in the code, can we guarantee the following statement always return true:

If ( A / B == A / B )

解决方案

A guarantee of behavior for a compiler requires some document specifying the behavior. The answer therefore depends on the programming language, and, if the specification of the programming language is inadequate, the answer depends on the specific compiler used.

The question does not identify any specific programming language, let alone any specific compiler. Some programming languages have standards that specify many aspects of their behavior, while some programming languages are informal and do not clearly document behavior.

In the latter category, Python says that floating-point behavior is derived from whatever platform it is running on. So we cannot easily be sure what Python will do.

The C standard is not completely clear about floating-point behavior. I opened this question to seek clarification, and, so far, my interpretation is that the standard ought to be interpreted as requiring implementations to use one format of their choice to evaluate floating-point operations of a particular type, but compilers have not historically conformed to this. For example, older versions of GCC could evaluate expressions with extended precision but convert to nominal precision at unpredictable times. This could result in A/B == A/B evaluating to false (even excluding NaNs, which I assume for purposes of discussion here).

The Java specification is more specific about floating-point operations and specifies conformance to IEEE 754, but it specifies FP-strict and not FP-strict modes, and a cursory examination suggests that not FP-strict mode could allow A/B to compare unequal to A/B.

这篇关于是否可以保证A / B的两倍始终等于A / B?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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