增加双精度值

Increasing the double precision values

我现在是运行一个特定迭代的程序。时间步长为 0.01。我想在到达特定时间时写一些信息。例如:

  program abc
  implicit none
  double precision :: time,step,target
  integer :: x

  time = 0.d0
  step = 0.01
  target = 5.d0

  do x = 1,6000
     time = time + step
     "some equations here to calculate the model parameters"
     if(time.eq.target)then
        write(*,*) "model parameters"
      endif
   enddo

但是,"time" 永远不会等于 1.0 或 2.0 等。它显示为“0.999999866”而不是“1.0”和“1.99999845”而不是“2.0”。

虽然我可以使用整数"x"来定义何时写入信息,但我更喜欢使用时间步长。另外,我可能想更改时间步长 (0.01/0.02/0.05/etc) 或目标 (5.0/6.0/8.0/etc)。

有谁知道如何解决这个问题?先谢谢了。

你已经发现了浮点运算!只要确保时间足够接近目标即可。

if(abs(time-target) < 0.5d0*step ) then ...

应该可以解决问题。

浮点运算并不完美,您的变量始终精确到一定的机器错误,具体取决于变量的数字格式(32、64、128 位)。下面的例子很好地说明了这个特点:

PROGRAM main 
    USE, INTRINSIC :: ISO_FORTRAN_ENV, qp => real128
    IMPLICIT NONE 

    REAL(qp) :: a, b, c 

    a = 128._qp      
    b = a/120._qp + 1  
    c = 120._qp*(b-1)  

    PRINT*, "a = ", a
    PRINT*, "c = ", c  
END PROGRAM main  

这是此程序的输出 gfortran v.4.6.3:

 a =    128.00000000000000000      
 c =    127.99999999999999999