What's the smallest non-zero, positive floating-point number in Perl?

Deadly 提交于 2019-12-01 19:47:27

The other answers are good. Here is how to find out the approximate ε if you did not know any of that information and could not post your question on SO ;-)

 #!/usr/bin/perl

use strict;
use warnings;

use constant MAX_COUNT => 2000;

my ($x, $c);

for (my $y = 1; $y; $y /= 2) {
    $x = $y;
    # guard against too many iterations
    last if ++$c > MAX_COUNT;
}

printf "%d : %.20g\n", $c, $x;

Output:

C:\Temp> thj
1075 : 4.9406564584124654e-324

According to perldoc perlnumber, Perl uses the native floating point format where native is defined as whatever the C compiler that was used to compile it used. If you are more worried about precision/accuracy than speed, take a look at bignum.

It may be important to note that that smallest number is what's called a subnormal number, and math done on it may produce surprising results:

$ perl -wle'$x = 4.94e-324; print for $x, $x*1.4, $x*.6'
4.94065645841247e-324
4.94065645841247e-324
4.94065645841247e-324

That's because it uses the smallest allowed (base-2) exponent and a mantissa of the form (base-2) 0.0000000...0001. Larger, but still subnormal, numbers will also have a mantissa beginning 0. and an increasing range of precision.

I actually don't know how perl represents floating point numbers (and I think this is something you configure when you build perl), but if we assume that IEEE 754 is used then epsilon for a 64 bit floating point number is 4.94065645841247E-324.

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