Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: what did I just see..?

by ikegami (Patriarch)
on Mar 22, 2021 at 08:05 UTC ( [id://11130079]=note: print w/replies, xml ) Need Help??


in reply to what did I just see..?

1/10, 8/10 and 1/100 are all periodic numbers in binary just like 1/3 is a periodic number in decimal.

____ 0.00011 # 1/10 ____ 0.1100 # 8/10 ____________________ 0.0000001010001111010111 # 1/100

As such, they can't be accurately represented as floating-point numbers.

$ perl -e'printf "%.100g\n", $ARGV[0]' 0.1 0.1000000000000000055511151231257827021181583404541015625 $ perl -e'printf "%.100g\n", $ARGV[0]' 0.8 0.8000000000000000444089209850062616169452667236328125 $ perl -e'printf "%.100g\n", $ARGV[0]' 0.01 0.01000000000000000020816681711721685132943093776702880859375

See What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Solution:

for (0..69) ( my $x = ( 80 - $_ ) / 100; say $x; }

This will prevent error from accumulating, keeping it under the default rounding. You could also perform more forgiving rounding than the default. Or you could avoid floating point numbers entirely (e.g. using rational number libraries).

Seeking work! You can reach me at ikegami@adaelis.com

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-03-29 10:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found