什么是Perl中最小的非零正浮点数? [英] What's the smallest non-zero, positive floating-point number in Perl?

查看:210
本文介绍了什么是Perl中最小的非零正浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl程序,可能偶尔会很小。由于四舍五入的错误,有时候其中一个可能性是零。我想检查以下内容:

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



$ b $ p
$ b

这很好,但我实际上看到Perl产生小于1e的数字-200(我刚刚看到一个8.14e-314飞过)。对于我的应用程序,我可以更改calculate_prob(),以便返回TINY_FLOAT的最大值和实际的概率,但是这让我很好奇在Perl中如何处理浮点数。



Perl中最小的正浮点值是多少?是平台依赖的吗?如果是这样,有没有一个快速的程序,我可以用它在我的机器上找出来?

解决方案

其他答案都很好。这里是如何找出近似ε如果你不知道这些信息,就不能在SO上发表你的问题; - )

 #!/ usr / bin / perl 

使用strict;
使用警告;

使用常数MAX_COUNT => 2000;

my($ x,$ c);

(my $ y = 1; $ y; $ y / = 2){
$ x = $ y;
#防止太多迭代
最后如果++ $ c> MAX_COUNT;
}

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

输出:

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


I have a program in Perl that works with probabilities that can occasionally be very small. 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). 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.

What's the smallest positive floating-point value in Perl? Is it platform-dependent? If so, is there a quick program that I can use to figure it out on my machine?

解决方案

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

这篇关于什么是Perl中最小的非零正浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆