浮点运算稳定吗? [英] Is floating point arithmetic stable?

查看:17
本文介绍了浮点运算稳定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道浮点数有精度,精度后面的数字不可靠.

I know that floating point numbers have precision and the digits after the precision is not reliable.

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

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

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

for example we have two float numbers x and y. Can we assume the result x/y from machine 1 is exactly the same as the result from machine 2? I.E. == comparison would return 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 位 - 而在其他情况下则不会.当满足以下任一条件时,这可能会导致看到不同的结果:

In particular, in some situations the JIT is permitted to use a more accurate intermediate representation - e.g. 80 bits when your original data is 64 bits - whereas in other situations it won't. That can result in seeing different results when any of the following is true:

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

来自 C# 5 规范第 4.1.6 节:

From the C# 5 specification section 4.1.6:

浮点运算可以以比运算结果类型更高的精度执行.例如,某些硬件体系结构支持扩展"或长双精度"浮点类型,其范围和精度比双精度类型更大,并使用这种精度更高的类型隐式执行所有浮点运算.只有在性能成本过高的情况下,才能使此类硬件架构以较低的精度执行浮点运算,而不是要求实现同时丧失性能和精度,C# 允许将更高精度的类型用于所有浮点运算.除了提供更精确的结果之外,这很少有任何可衡量的影响.但是,在 x * y/z 形式的表达式中,乘法产生的结果超出双精度范围,但随后的除法将临时结果带回双精度范围,事实是以更高范围的格式计算表达式可能会导致产生有限结果而不是无穷大.

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.

这篇关于浮点运算稳定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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