For Programmers: Free Programming Magazines  


Home > Archive > PERL CGI Beginners > December 2005 > Hi, strange problem on calculation









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Hi, strange problem on calculation
webmaster@echtwahr.com

2005-12-07, 7:55 am

Hi,

I don't know why the result of my calculation doesn't make sense!


foreach('0.43','-0.12','-0.08','-0.17','-0.06') {
$value = $value + ($_);
}
print $value . "<br>";

Value = -2.77555756156289e-17
Should be 0.00


My Perl Version is:
perl -V
Summary of my perl5 (revision 5 version 8 subversion 4)



Mit freundlichen Grüssen
Ihr echtwahr.Webmaster

------------------------
http://www.echtwahr.de
http://www.echtwahr.com



Owen Cook

2005-12-07, 7:55 am


On Wed, 7 Dec 2005 webmaster@echtwahr.com wrote:

> Hi,
>
> I don't know why the result of my calculation doesn't make sense!
>
>
> foreach('0.43','-0.12','-0.08','-0.17','-0.06') {
> $value = $value + ($_);
> }
> print $value . "<br>";
>
> Value = -2.77555756156289e-17
> Should be 0.00



What is the difference between -2.77555756156289e-17 and 0.00?

It's all to do with the way numbers are represented in computers.

Do a "perldoc -f sprintf" and have a read.


Owen

Paul Lalli

2005-12-07, 6:55 pm

webmaster@echtwahr.com wrote:
> I don't know why the result of my calculation doesn't make sense!
>
>
> foreach('0.43','-0.12','-0.08','-0.17','-0.06') {
> $value = $value + ($_);
> }
> print $value . "<br>";
>
> Value = -2.77555756156289e-17
> Should be 0.00


Read the FAQ about this topic:

perldoc -q numbers
Why am I getting long decimals (eg, 19.9499999999999)
instead of the numbers I should be getting (eg, 19.95)?


Paul Lalli

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com