Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: IEEE-754 calculation - best way?

by BrowserUk (Pope)
on Jan 30, 2013 at 22:40 UTC ( #1016169=note: print w/ replies, xml ) Need Help??


in reply to IEEE-754 calculation - best way?

if I multiply 0.29 with 50, I get 14.5: Only with this line: my $num4 = sprintf ("%.64f", $num7); I get the exact result in "double" (14.999...).

The only difference between:

print 0.29 * 50;; 14.5

And:

printf "%.20f\n", 0.29 * 50;; 14.49999999999999800000

is what gets printed out; not what is calculated and stored internally.

All floating point calculations are done internally using IEEE754 semantics; if you want to see the full internal results use printf to display the results.

As for your perceived difference when gratuitously using eval:

printf "%.20f\n", eval eval( 0.29 ) * eval( 50 );; 14.50000000000000000000

The first thing to note is that the first two evals make no difference whatsoever:

printf "%.20f\n", eval 0.29 * 50;; 14.50000000000000000000

And the reason for that difference is because (in this form) eval expects a string. So the result of the multiplication (eval( 0.29 ) * eval( 50 )) is converted to a string -- using the same rules as print -- before being passed to the final eval.

You get identically different results if you do:

$n = 0.29 * 50; printf "%.20f\n", "$n";; 14.50000000000000000000

Because the internal (IEEE754) representation has been lost by the conversion to a string.

Bottom line: Stop worrying about it. Do your floating point math in the usual way (no eval's; no stringifications), secure in the full IEEE754 semantics will be used internally; and then use printf/sprintf (*only*) when you need to display them.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.


Comment on Re: IEEE-754 calculation - best way?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (11)
As of 2015-07-02 06:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (30 votes), past polls