简体   繁体   English

浮点运算的精度

[英]Precision of floating point operations

Floating point operations are typically approximations to the corresponding arithmetic operations, because in many cases the precise arithmetic result cannot be represented by the internal number format. 浮点运算通常是对应算术运算的近似值,因为在许多情况下,精确的算术结果无法用内部数字格式表示。 But what happens if I have a program where all numbers can actually be represented exactly by IEEE 754 single precision? 但是,如果我有一个程序,其中所有数字实际上都可以用IEEE 754单精度精确表示,会发生什么? Consider for example this: 考虑以下示例:

float a = 7;
float b = a / 32.0;
float c = a + b;
float d = c - a;
assert( d == b );

Is it safe to assume that within this and similar cases, the result of the numerical calculation is identical to the exact arithmetic result? 是否可以安全地假设在这种情况下以及类似情况下,数值计算的结果与精确的算术结果相同? I think this sort of code would work on every actual machine. 我认为这种代码可以在每台实际机器上使用。 Is this correct? 这个对吗?

Edit This question is not about what the standard says, but rather about the real world. 编辑这个问题不是关于标准所说的,而是关于现实世界的。 I'm well aware that in theory one could create a conforming engine where this would fail. 我很清楚, 从理论上讲,可以创建一个符合标准的引擎,而这会失败。 I don't care, but rather I wonder if this works on existing machines. 我不在乎,但是我想知道这是否可以在现有计算机上运行。

否,因为c ++标准不需要以IEEE 754格式存储浮点值。

"Real" machines are quite careful in implementing the standard exactly (just remember the Pentium division bug ). “真实”机器在准确地执行标准时非常小心(只记得Pentium的错误 )。 But be careful to check, the i386 line of machines did use some extra bits in its registers, which were cut off when asigning to/from memory, so computations done only in registers gave different results than if some intermediate results where spilled to memory. 但是要小心检查,i386系列机器确实在其寄存器中使用了一些额外的位,这些位在分配给内存或从内存中分配时会被切断,因此,与在某些中间结果溢出到内存中相比,仅在寄存器中执行的计算得出的结果有所不同。

Also check out David Goldberg's What every computer scientist should know about floating point arithmetic . 另请参阅David Goldberg的“每位计算机科学家都应了解的浮点算术知识”

In any case, it doesn't make any sense to "round" (or otherwise mangle) a number that can be represented exactly. 在任何情况下,“舍入”(或捣乱)可以精确表示的数字都没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM