Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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


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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016169]
[1nickt]: stevieb it's just a simple web page with a POST form. You can set the attribute so when the user's browser opens a file manager to select a file to upload, it will only show those o f the type you want to get.
[1nickt]: Question for my learned friends: is there a word meaning "CSV-like" i.e. I want to say that I accept CSV files, but the separator doesn;t have to be a comma. Or is that implicit these days?
[chacham]: dsv

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2017-07-22 18:49 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (340 votes). Check out past polls.