本文介绍了测试浮点数相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Windows 7(32位)下使用MinGW中的gfortran来编译Fortran代码。这是文件 testequal.f
中包含的最小代码: 程序testequal
real * 8 a1,a2
a1 = 0.3d0
a2 = 0.7d0
写(*,*)1.d0 $ b * b写(*,*)a1 + a2
写(*,*)a1 + a2.eq.1.0
写(*,*)a1 + a2.eq.1.d0
与
<$ p $输出为: gfortran testequal.f -std = legacy
/ p>
1.0000000000000000
1.0000000000000000
F
F
但我期望两个布尔值都是 T
(true)。这里有什么问题?
解决方案
极少数例外情况下,请不要比较浮点数以确保相等。有限精度浮点运算的规则与实数运算的规则不尽相同。比较数字与宽容,例如,如果(abs(sum - 1.0)
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?
解决方案
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 ) ...
这篇关于测试浮点数相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!