How many significant digits do floats and doubles have in java?

前端 未结 6 1435
余生分开走
余生分开走 2020-11-22 09:28

Does a float have 32 binary digits and a double have 64 binary digits? The documentation was too hard to make sense of.

Do all of the bits translate to significant d

6条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 10:08

    A 32-bit float has about 7 digits of precision and a 64-bit double has about 16 digits of precision

    Long answer:

    Floating-point numbers have three components:

    1. A sign bit, to determine if the number is positive or negative.
    2. An exponent, to determine the magnitude of the number.
    3. A fraction, which determines how far between two exponent values the number is. This is sometimes called “the significand, mantissa, or coefficient”

    Essentially, this works out to sign * 2^exponent * (1 + fraction). The “size” of the number, it’s exponent, is irrelevant to us, because it only scales the value of the fraction portion. Knowing that log₁₀(n) gives the number of digits of n,† we can determine the precision of a floating point number with log₁₀(largest_possible_fraction). Because each bit in a float stores 2 possibilities, a binary number of n bits can store a number up to 2ⁿ - 1 (a total of 2ⁿ values where one of the values is zero). This gets a bit hairier, because it turns out that floating point numbers are stored with one less bit of fraction than they can use, because zeroes are represented specially and all non-zero numbers have at least one non-zero binary bit.‡

    Combining this, the digits of precision for a floating point number is log₁₀(2ⁿ), where n is the number of bits of the floating point number’s fraction. A 32-bit float has 24 bits of fraction for ≈7.22 decimal digits of precision, and a 64-bit double has 53 bits of fraction for ≈15.95 decimal digits of precision.

    For more on floating point accuracy, you might want to read about the concept of a machine epsilon.


    † For n ≥ 1 at least — for other numbers your formula will look more like ⌊log₁₀(|n|)⌋ + 1.

    ‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)

提交回复
热议问题