简体   繁体   English

Perl中最小的非零,正浮点数是多少?

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

I have a program in Perl that works with probabilities that can occasionally be very small. 我在Perl中有一个程序可以处理偶尔会非常小的概率。 Because of rounding error, sometimes one of the probabilities comes out to be zero. 由于舍入误差,有时其中一个概率为零。 I'd like to do a check for the following: 我想检查以下内容:

use constant TINY_FLOAT => 1e-200;
my $prob = calculate_prob();
if ( $prob == 0 ) {
    $prob = TINY_FLOAT;
}

This works fine, but I actually see Perl producing numbers that are smaller than 1e-200 (I just saw a 8.14e-314 fly by). 这工作正常,但我实际上看到Perl生成的数字小于1e-200(我刚看到8.14e-314飞过)。 For my application I can change calculate_prob() so that it returns the maximum of TINY_FLOAT and the actual probability, but this made me curious about how floating point numbers are handled in Perl. 对于我的应用程序,我可以更改calculate_prob(),以便它返回TINY_FLOAT的最大值和实际概率,但这让我对如何在Perl中处理浮点数感到好奇。

What's the smallest positive floating-point value in Perl? Perl中最小的正浮点值是多少? Is it platform-dependent? 它是平台依赖的吗? If so, is there a quick program that I can use to figure it out on my machine? 如果有,是否有一个快速程序,我可以用来在我的机器上找出它?

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. 根据perldoc perlnumber ,Perl使用本机浮点格式,其中native定义为用于编译它的C编译器。 If you are more worried about precision/accuracy than speed, take a look at bignum . 如果您更担心精度/准确度而不是速度,请查看bignum

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 ;-) 如果您不知道任何该信息并且无法在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

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. 那是因为它使用了最小的允许(base-2)指数和形式的尾数(base-2)0.0000000 ... 0001。 Larger, but still subnormal, numbers will also have a mantissa beginning 0. and an increasing range of precision. 较大但仍然是次正规的数字也将具有从0开始的尾数和不断增加的精度范围。

我实际上不知道perl如何表示浮点数(我认为这是你在构建perl时配置的),但是如果我们假设使用了IEEE 754,那么epsilon对于64位浮点数是4.94065645841247E-324 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM