Does float have a negative zero? (-0f)

后端 未结 10 740
离开以前
离开以前 2020-11-28 09:36

IEEE floating point numbers have a bit assigned to indicate the sign, which means you can technically have different binary representations of zero (+0 and -0). Is there an

10条回答
  •  猫巷女王i
    2020-11-28 10:22

    Is there an arithmetic operation I could do for example in C which result in a negative zero floating point value?

    Sure:

    float negativeZero = -10.0e-30f * 10.0e-30f;
    

    The mathematically precise result of the multiplication is not representable as a floating-point value, so it rounds to the closest representable value, which is -0.0f.

    The semantics of negative zero are well defined by the IEEE-754 standard; the only real observable way in which its behavior differs from that of zero in arithmetic expression is that if you divide by it, you will get a different sign of infinity. For example:

    1.f /  0.f --> +infinity
    1.f / -0.f --> -infinity
    

    Comparisons and addition and subtraction with -0.f give the same result as they would with +0.f (in the default rounding mode). Multiplication can preserve the sign of zero, but as noted, it generally isn't observable.

    There are some math library functions whose behavior can vary depending on the sign of zero. For example:

    copysignf(1.0f, 0.0f) -->  1.0f
    copysignf(1.0f,-0.0f) --> -1.0f
    

    This is more common in the complex functions:

    csqrtf(-1.0f + 0.0f*i) --> 0.0f + 1.0f*i
    csqrtf(-1.0f - 0.0f*i) --> 0.0f - 1.0f*i
    

    In general, however, you shouldn't need to worry about negative zero.

提交回复
热议问题