<分区>
我知道 float 是有精度的,精度后面的数字不靠谱。
但如果用于计算数字的方程式相同呢?我可以假设结果也是一样的吗?
例如我们有两个 float x
和y
。我们可以假设机器 1 的结果 x/y
与机器 2 的结果完全相同吗? IE。 ==
比较会返回 true
标签 c# floating-point
<分区>
我知道 float 是有精度的,精度后面的数字不靠谱。
但如果用于计算数字的方程式相同呢?我可以假设结果也是一样的吗?
例如我们有两个 float x
和y
。我们可以假设机器 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 ......)来自 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/