Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create or test for NaN or infinity in Perl?

Tags:

nan

perl

infinity

How do I create or test for NaN or infinite values in Perl?

like image 652
ysth Avatar asked Jul 26 '09 23:07

ysth


2 Answers

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.

like image 196
Hynek -Pichi- Vychodil Avatar answered Sep 24 '22 02:09

Hynek -Pichi- Vychodil


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 
like image 33
ysth Avatar answered Sep 26 '22 02:09

ysth