Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 'NaN' numeric according to the warnings pragma?

Tags:

nan

perl

I'm a little surprised (and scared) by the fact that the warnings pragma doesn't complain about 'NaN' and 'nan' being non-numeric.

Why does warnings not emit the customary 'Argument isn't numeric in addition (+) for them?

Test Case

$ perl -Mstrict -wE 'say 0+$_ for qw/string NaN nan fail/;'
Argument "string" isn't numeric in addition (+) at -e line 1.
0
0
0
Argument "fail" isn't numeric in addition (+) at -e line 1.
0
like image 999
Zaid Avatar asked Jul 05 '12 13:07

Zaid


2 Answers

From perlop

Binary "<=>" returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. If your platform supports NaNs (not-a-numbers) as numeric values, using them with "<=>" returns undef. NaN is not "<", "==", ">", "<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaN returns true, as does NaN != anything else.

If your platform doesn't support NaNs then NaN is just a string with numeric value 0.

NaN behaves different on different platforms. It is in a way numerical as it can act as such in numerical operations. But it is also really not a number as it has undefined value.

Furthermore its behaviour is not portable as:

perl -E "say 'yes' if 0 == 'NaN'"

could yield different results on different platforms unless you use Perl 5.22 or newer.

like image 90
matthias krull Avatar answered Oct 24 '22 05:10

matthias krull


"Not a number" is the long name for the value most often represented as "NaN". See also the wikipedia article. Computing with NaN is actually meaningful (it even has an actual bit-level representation in IEEE754).

like image 7
2v0mjdrl Avatar answered Oct 24 '22 05:10

2v0mjdrl