fortran条件语句如何处理浮点数据类型? [英] How do fortran conditional statements handle floating-point datatypes?
问题描述
如果条件语句比较两个实数(一个是从导入模块中分配和初始化的数组中读取的),那么失败时,我有一个简单的它不应该。
在什么情况下会发生这种情况?
我正在使用英特尔编译器。
编辑:
为进一步说明,我正在做类似这样的事情:
if(12.2272> = -5.0000)然后
做某事
else
print *,'fail'
endif
我得到失败
。当我只评估>
而不是> =
时也是如此。$ b $通常,由于浮点数的内在不精确性,通常只能对浮点数进行可靠的比较。一般来说,除了一些特殊情况之外,你不应该比较所有的平等情况,除非一些特殊情况,比如直接读取的值与一些小整数,通常为0. b
$ b
使用其中一个数字进行平均计算,根本不会进行比较。有一些宽容,你可以使用:
if(abs(ab)
其中eps是一些小数字。它可以是 epsilon
内部函数结果的一些(甚至很大)倍数。
阅读一些文章关于浮点数,如 http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
您可以尝试使用这个小程序查看浮点数的典型问题
real x
integer i
x = 0
do i = 1,10
x = x + 0.1
end do
print *,x,x == 1
end
I have a simple if
conditional statement that is comparing two real numbers (one is read from an array that is allocated and initialized in an imported module) that is failing when it shouldn't.
Under what circumstances might this happen?
I'm using the Intel compiler.
Edit: For further clarification, I am doing something like this:
if (12.2272 >= -5.0000) then
do something
else
print *, 'fail'
endif
I'm getting fail
. The same goes for when I evaluate with only >
rather than >=
.
Usually, you can compare floating point numbers reliably only with some tolerance, because of their inherent non-preciseness. Generally, you shouldn't compare for equality at all except some special cases, like comparing a directly read value with some small integer, typically 0.
If you did any non-trivial computing with one of the numbers, don't compare for equality at all. With some tolerance, you can use:
if (abs(a-b)<eps) ...
where eps is some small number. It can be some (even large) multiple of the epsilon
intrinsic function result.
It's good to read some article about floating points, like http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
You can try this little program to see the typical problem with floating point numbers
real x
integer i
x = 0
do i = 1,10
x = x + 0.1
end do
print *, x, x==1
end
这篇关于fortran条件语句如何处理浮点数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!