为什么我在Perl中减去同一个浮点数的时候得不到零呢? [英] Why don't I get zero when I subtract the same floating point number from itself in Perl?

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

问题描述


可能存在重复:



为什么ghci说1.1 + 1.1 + 1.1> 3.3是真的?




 #!/ 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?
任何人都可以解释这个请求......

解决方案

每个计算机科学家应该知道什么是浮点运算

<为什么C#中的浮点运算不精确?

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


Possible Duplicates:
Why is floating point arithmetic in C# imprecise?
Why does ghci say that 1.1 + 1.1 + 1.1 > 3.3 is True?

#!/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中减去同一个浮点数的时候得不到零呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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