在IEEE 754中,为什么添加负零会导致无操作,而添加正零却不会呢? [英] In IEEE 754, why does adding negative zero result in a no-op but adding positive zero does not?
问题描述
我正在研究Rust中的一些算法(尽管语言对我的问题并不重要).考虑代码:
I'm toying with some algorithm in Rust (though the language doesn't really matter for my question). Consider the code:
#[no_mangle]
pub fn test(x: f32) -> f32 {
let m = 0.;
x + m
}
fn main() {
test(2.);
}
它会产生以下LLVM IR和相应的x86_64 asm(启用优化):
It produces the following LLVM IR and corresponding x86_64 asm (optimizations enabled):
;; LLVM IR
define float @test(float %x) unnamed_addr #0 {
start:
%0 = fadd float %x, 0.000000e+00
ret float %0
}
;; x86_64
; test:
xorps xmm1, xmm1
addss xmm0, xmm1
ret
如果将let m = 0.;
更改为let m = -0.;
,浮点加法将被优化:
If I change let m = 0.;
to let m = -0.;
the floating point addition is optimized away:
;; LLVM IR
define float @test(float returned %x) unnamed_addr #0 {
start:
ret float %x
}
;; x86_64
; fn disappears entirely
推荐答案
在默认的最近舍入模式下,大多数高级语言都专门支持,因为它们不提供禁用浮点优化的选项在其他模式下不适用(我认为Rust属于此类),添加-0.0
不会对任何浮点值产生影响(忽略有关NaN的小细节),而添加+0.0
会对-0.0
产生影响(-0.0 + (+0.0)
的结果是+0.0
).
In the default round-to-nearest mode, that most high-level languages support exclusively, because they do not provide options to disable floating-point optimizations that become inapplicable in other modes—I assume that Rust falls in this category—, adding -0.0
happens to have no effect on any floating-point value (omitting small details about NaNs), whereas adding +0.0
has an effect on -0.0
(the result of -0.0 + (+0.0)
is +0.0
).
这篇关于在IEEE 754中,为什么添加负零会导致无操作,而添加正零却不会呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!