简体   繁体   English

fortran条件语句如何处理浮点数据类型?

[英]How do fortran conditional statements handle floating-point datatypes?

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. 我有一个简单的if条件语句,该语句比较两个实数(一个是从分配的数组中读取的,并在导入的模块中初始化),它不应该失败。

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 . 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. 通常,除了某些特殊情况外,您根本不应该比较相等性,例如将直接读取的值与一些小的整数(通常为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. 其中eps是一些小数字。 It can be some (even large) multiple of the epsilon intrinsic function result. 它可能是epsilon内在函数结果的几倍(甚至很大)。

It's good to read some article about floating points, like http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems 最好阅读一些有关浮点的文章,例如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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM