为什么我在Perl中减去同一个浮点数的时候得不到零呢

为什么我在Perl中减去同一个浮点数的时候得不到零呢

本文介绍了为什么我在Perl中减去同一个浮点数的时候得不到零呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 #!/ usr / bin / perl 
$ l1 =0 + 0.590580 + 0.583742 + 0.579787 + 0.564928 + 0.504538 + 0.459805 + 0.433273 + 0.384211 + 0.3035810;
$ l2 =0 + 0.590580 + 0.583742 + 0.579788 + 0.564928 + 0.504538 + 0.459805 + 0.433272 + 0.384211 + 0.3035810;
$ val1 = eval($ l1);
$ val2 = eval($ l2);
$ diff =(($ val1 - $ val2)/ $ val1)* 100; $($ val1 - $ val2)/ $ val1)* 100 ==> $ diff \ n;

令人惊讶的是,输出结果是
<$ ((4.404445 - 4.404445)/4.404445)* 100 ==> -2.01655014354845e-14。

是不是应该是ZERO?
任何人都可以解释这个请求......

解决方案





这不是Perl相关的,而是浮点相关的。


#!/usr/bin/perl
$l1 = "0+0.590580+0.583742+0.579787+0.564928+0.504538+0.459805+0.433273+0.384211+0.3035810";
$l2 = "0+0.590580+0.583742+0.579788+0.564928+0.504538+0.459805+0.433272+0.384211+0.3035810";
$val1 = eval ($l1);
$val2 = eval ($l2);
$diff = (($val1 - $val2)/$val1)*100;
print " (($val1 - $val2)/$val1)*100 ==> $diff\n";

Surprisingly the output ended up to be

((4.404445 - 4.404445)/4.404445)*100 ==> -2.01655014354845e-14.

Is it not supposed to be a ZERO????Can any one explain this please......

解决方案

What every computer scientist should know about floating point arithmetic

See Why is floating point arithmetic in C# imprecise?

This isn't Perl related, but floating point related.

这篇关于为什么我在Perl中减去同一个浮点数的时候得不到零呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:48