'How to find NaN in an array and stop once found?
Say, I want a routine to stop once a not-a-number is found in an array. How can I do this?
if (array(i) .eq. NA) ...
seems not work.
The array
is an array of floating point numbers:
REAL :: array(35)
Solution 1:[1]
If you are really looking for NaN
s and you have an up to date compiler then the ieee_is_nan()
function should do the trick. I think you'll need to use ieee_arithmetic
or one of the other intrinsic IEEE modules.
If your compiler is not so new, it may have the commonly-implemented but non-standard isnan()
function.
Solution 2:[2]
You question is not very well constrained. Is array
an array of strings? e.g.
character(len=20) :: array(40)
If this is the case, you should be able to just do:
do i=1,40
if(array(i).eq."NA")then
exit
else
!do something else
endif
enddo
If this is an array of floating point numbers (and NA is defined to be some floating point constant), you might want to be careful as floating-point operations are rarely exact and rounding error can cause a calculation that would mathematically be equivalent to actually evaluate to different values. In other words, the solution to this problem really depends on how NA
and array
are declared...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | High Performance Mark |
Solution 2 | mgilson |