In IEEE 754, why does adding negative zero result in a no-op but adding positive zero does not?

跟風遠走 提交于 2019-12-11 00:00:39

问题


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.);
}

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

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

回答1:


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).



来源:https://stackoverflow.com/questions/48255293/in-ieee-754-why-does-adding-negative-zero-result-in-a-no-op-but-adding-positive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!