Perl:如何比较浮点数 [英] Perl: How to compare floating numbers

查看:225
本文介绍了Perl:如何比较浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的Perl脚本。但是,它不打印1。我做了一些研究,似乎是因为浮点数的IEEE表示。那么,有没有更好的方法来比较Perl中的浮点数?



$ p $ for(my $ tmp = 0.1; $ tmp < = 1; $ tmp + = 0.05){print $ tmp。\\\
}

输出:

  0.1 
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95


解决方案

使用浮点数的所有计算都可能有精度错误,如果重复使用这些结果,那么这些精度错误就会叠加起来。有一点要学习,就是永远不要使用float作为循环控制变量。



使用类似于



<$对于(my $ tmp = 2; $ tmp< = 20; tmp ++){
print $ tmp / 20.0,\\\
; p $ p>
}

尽你所能。如果你真的需要比较两个浮动($ a,$ b)类似于

  if(abs($ a  -  $ b)< 0.000001)

只有真正有效的东西 - 但是,这也可能有问题,取决于差异可以算作一个真正的差异有多小。


I wrote the following Perl script. However, it does not print "1". I did some research and it seems it is because of the IEEE representation of floating-point number. So, is there a better way to compare floating-point numbers in Perl?

for (my $tmp = 0.1; $tmp <= 1; $tmp+=0.05){print $tmp."\n"}

Output:

0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
0.5
0.55
0.6
0.65
0.7
0.75
0.8
0.85
0.9
0.95

解决方案

All computations that use floating point numbers may have precision errors, and if you reuse the results, those precision erros stack up. One thing to learn from that is to never use a float as a loop control variable.

Use something like

for (my $tmp=2; $tmp<=20; tmp++) {
    print $tmp/20.0, "\n";
}

whereever you can. If you really really need to compare two floats ($a, $b) something like

if (abs($a - $b) < 0.000001)

is the only thing that really works -- however, this might have issues as well depending on how small the difference can be to count as a real difference.

这篇关于Perl:如何比较浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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