c# - 浮点运算稳定吗?

标签 c# floating-point

<分区>

我知道 float 是有精度的,精度后面的数字不靠谱。

但如果用于计算数字的方程式相同呢?我可以假设结果也是一样的吗?

例如我们有两个 float xy。我们可以假设机器 1 的结果 x/y 与机器 2 的结果完全相同吗? IE。 == 比较会返回 true

最佳答案

But what if the equation used to calculate the number is the same? can I assume the outcome would be the same too?

不,不一定。

特别是,在某些情况下,允许 JIT 使用更准确的中间表示 - 例如当原始数据为 64 位时为 80 位 - 而在其他情况下则不会。当以下任一情况为真时,这可能会导致看到不同的结果:

  • 您的代码略有不同,例如使用局部变量而不是字段,这可以更改值是否存储在寄存器中。 (这是一个相对明显的例子;还有其他更微妙的例子可以影响事情,例如方法中存在 try block ......)
  • 您在不同的处理器上执行(我曾经观察过 AMD 和 Intel 之间的差异;同一制造商的不同 CPU 之间也可能存在差异)
  • 您正在执行不同的优化级别(例如,是否在调试器下)

来自 C# 5 规范第 4.1.6 节:

Floating-point operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an "extended" or "long double" floating-point type with greater range and precision than the double type, and implicitly perform all floating-point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating-point operations with less precision, and rather than require an implementation to forfeit both performance and precision, C# allows a higher precision type to be used for all floating-point operations. Other than delivering more precise results, this rarely has any measurable effects. However, in expressions of the form x * y / z, where the multiplication produces a result that is outside the double range, but the subsequent division brings the temporary result back into the double range, the fact that the expression is evaluated in a higher range format may cause a finite result to be produced instead of an infinity.

关于c# - 浮点运算稳定吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48384335/

相关文章:

c# - C# 中的某些内容可以在运行时更改 float 比较行为吗? [x64]

c# - JSon.Net 如何让 $type 只用于反序列化

C++,如何优化浮点算术运算?

c++ - C++中奇怪的天花板错误

c# - 如何在不损失质量的情况下将 jpeg 转换为字节数组

c# - 加载 ASP.NET DropDownList

c# - 在运行时替换 href 值

java - 关系运算符在哪些方面不遵守浮点值的 compareTo 契约?

c - 为什么 fmax(a, b) 返回较小的(负)零以及如何干净地解决它?

delphi - 在Delphi中比较货币值时如何避免舍入问题?