Why do I need 17 significant digits (and not 16) to represent a double?

前端 未结 5 1499
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 08:55

Can someone give me an example of a floating point number (double precision), that needs more than 16 significant decimal digits to represent it?

I have found in thi

5条回答
  •  隐瞒了意图╮
    2020-12-29 09:08

    The correct answer is the one by Nemo above. Here I am just pasting a simple Fortran program showing an example of the two numbers, that need 17 digits of precision to print, showing, that one does need (es23.16) format to print double precision numbers, if one doesn't want to loose any precision:

    program test
    implicit none
    integer, parameter :: dp = kind(0.d0)
    real(dp) :: a, b
    a = 1.8014398509481982e+16_dp
    b = 1.8014398509481980e+16_dp
    print *, "First we show, that we have two different 'a' and 'b':"
    print *, "a == b:", a == b, "a-b:", a-b
    print *, "using (es22.15)"
    print "(es22.15)", a
    print "(es22.15)", b
    print *, "using (es23.16)"
    print "(es23.16)", a
    print "(es23.16)", b
    end program
    

    it prints:

    First we show, that we have two different 'a' and 'b':
    a == b: F a-b:   2.0000000000000000     
    using (es22.15)
    1.801439850948198E+16
    1.801439850948198E+16
    using (es23.16)
    1.8014398509481982E+16
    1.8014398509481980E+16
    

提交回复
热议问题