Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an inf constant in Perl?

Tags:

perl

infinity

I'm initialising a list with infinities for an algorithm. Writing $x = 9**9**9 feels unintuitive, and also, I might want to use BigInt in the future. 1/0 throws an error.

What's the canonical way to get inf?

like image 975
Andreas Avatar asked Nov 30 '12 12:11

Andreas


2 Answers

You can use the special string "inf":

perl -E'say "inf" + 1'
inf
perl -E'say 1 / "inf"'
0

et cetera.

Other special strings include +inf, -inf, nan. Of course this also works with bignum or bigint pragmas. However, these pragmas export equivalent functions inf and NaN so that you can use barewords.

Edit

As @ikegami pointed out, there doesn't seem to be a portable way of accomplishing true infinities without a module. I just waded through this interesting perlmonks thread, but it doesn't get less confusing. Perhaps the best solution would be to accept the performance penalty and use big{num,int,rat} from the start, but use no big{num,int,rat} in scopes where they aren't required.

like image 164
amon Avatar answered Oct 10 '22 21:10

amon


I've used bigrat to do this. It's hard to tell what features -E is enabling.

use bigrat;
use feature qw(say);

say inf + inf;
say 9**99 / -inf();  #Perl doesn't always like "-inf" by itself

use bigrat; has been around for a long time, so it should be pretty portable.

like image 34
David W. Avatar answered Oct 10 '22 22:10

David W.