Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: adding numbers and floating point errors

by ikegami (Patriarch)
on Nov 22, 2006 at 22:18 UTC ( [id://585629]=note: print w/replies, xml ) Need Help??


in reply to adding numbers and floating point errors

If you really have a loop and you want to avoid the accumulation of error, you can avoid use an integer as the loop counter, and compute the current value of the real from the integer.

# Loop over [0.00..1.00] by 0.05 for (my $i = 0; $i <= 100; $i += 5) { my $x = $i / 100; printf("[%d] x= %g (%20.40f)\n", ++$c, $x, $x); }
# Loop over [0.00..1.00] by 0.05 for (my $i = 0; $i <= 20; $i++) { my $x = $i / 20; printf("[%d] x= %g (%20.40f)\n", $i+1, $x, $x); }
# Loop over [0.00..1.00] by 0.05 for (0..20) { my $x = $_ / 20; printf("[%d] x= %g (%20.40f)\n", $_+1, $x, $x); }

All of the above output the following:

[1] x= 0 (0.0000000000000000000000000000000000000000) [2] x= 0.05 (0.0500000000000000030000000000000000000000) [3] x= 0.1 (0.1000000000000000100000000000000000000000) [4] x= 0.15 (0.1499999999999999900000000000000000000000) [5] x= 0.2 (0.2000000000000000100000000000000000000000) [6] x= 0.25 (0.2500000000000000000000000000000000000000) [7] x= 0.3 (0.2999999999999999900000000000000000000000) [8] x= 0.35 (0.3499999999999999800000000000000000000000) [9] x= 0.4 (0.4000000000000000200000000000000000000000) [10] x= 0.45 (0.4500000000000000100000000000000000000000) [11] x= 0.5 (0.5000000000000000000000000000000000000000) [12] x= 0.55 (0.5500000000000000400000000000000000000000) [13] x= 0.6 (0.5999999999999999800000000000000000000000) [14] x= 0.65 (0.6500000000000000200000000000000000000000) [15] x= 0.7 (0.6999999999999999600000000000000000000000) [16] x= 0.75 (0.7500000000000000000000000000000000000000) [17] x= 0.8 (0.8000000000000000400000000000000000000000) [18] x= 0.85 (0.8499999999999999800000000000000000000000) [19] x= 0.9 (0.9000000000000000200000000000000000000000) [20] x= 0.95 (0.9499999999999999600000000000000000000000) [21] x= 1 (1.0000000000000000000000000000000000000000)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://585629]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2024-04-25 23:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found