Is there an inf constant in Perl?

十年热恋 提交于 2019-12-10 12:29:17

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13645034/is-there-an-inf-constant-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!