How do I create or test for NaN or infinite values in Perl?
print "Is NaN\n" if $a eq 'nan'; print "Is Inf\n" if $a eq 'inf' or $a eq '-inf';
EDIT: Fixed for negative infinity.
Here's a fairly reliable way:
my $inf = 9**9**9; my $neginf = -9**9**9; my $nan = -sin(9**9**9); sub isinf { $_[0]==9**9**9 || $_[0]==-9**9**9 } sub isnan { ! defined( $_[0] <=> 9**9**9 ) } # useful for detecting negative zero sub signbit { substr( sprintf( '%g', $_[0] ), 0, 1 ) eq '-' } for my $num ( $inf, $neginf, $nan ) { printf("%s:\tisinf: %d,\tisnan: %d,\tsignbit: %d\n", $num, isinf($num), isnan($num), signbit($num)); }
Output is:
inf: isinf: 1, isnan: 0, signbit: 0 -inf: isinf: 1, isnan: 0, signbit: 1 nan: isinf: 0, isnan: 1, signbit: 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With