Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

fortran - Testing floating point numbers equality

I am using gfortran in MinGW under Windows 7 (32bit) to compile Fortran code. Here is the minimal code contained in the file testequal.f:

      program testequal
      real*8 a1, a2

      a1 = 0.3d0
      a2 = 0.7d0

      write(*,*) 1.d0
      write(*,*) a1+a2
      write(*,*) a1+a2.eq.1.0
      write(*,*) a1+a2.eq.1.d0
      end

Compiled with

gfortran testequal.f -std=legacy

the output is:

1.0000000000000000
1.0000000000000000
F
F

But I expect the two booleans to be both T (true). What is the problem here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With rare exceptions, don't compare floating point numbers for exact equality. The rules of finite-precision floating point arithmetic are not the same are the rules of real number arithmetic. Compare numbers with a tolerance, e.g.,

sum = a1 + a2
if ( abs (sum - 1.0) < 1.0D-5 ) ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...