Why don't I get zero when I subtract the same floating point number from itself in Perl? [duplicate]

女生的网名这么多〃 提交于 2019-11-28 14:37:27
CB Bailey

It's pretty close to zero, which is what I'd expect.

Why's it supposed to be zero? 0.579787 != 0.579788 and 0.433273 != 0.433272. It's likely that none of these have an exact floating point representation so you should expect some inaccuracies.

From perlfaq4's answer to Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?:


Internally, your computer represents floating-point numbers in binary. Digital (as in powers of two) computers cannot store all numbers exactly. Some real numbers lose precision in the process. This is a problem with how computers store numbers and affects all computer languages, not just Perl.

perlnumber shows the gory details of number representations and conversions.

To limit the number of decimal places in your numbers, you can use the printf or sprintf function. See the "Floating Point Arithmetic" for more details.

printf "%.2f", 10/3;

my $number = sprintf "%.2f", 10/3;

When you change the two strings to be equal (there are 2 digits different between $l1 and $l2) it does indeed result in zero.

What it is demonstrating is that you can create 2 different floating point numbers ($val1 and $val2) that look the same when printed out, but internally have a tiny difference. These differences can be magnified up if you're not careful.

Vinko Vrsalovic posted some good links to explain why.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!