<?xml version="1.0" encoding="windows-1252"?>
<node id="1016169" title="Re: IEEE-754 calculation - best way?" created="2013-01-30 17:40:20" updated="2013-01-30 17:40:20">
<type id="11">
note</type>
<author id="171588">
BrowserUk</author>
<data>
<field name="doctext">
&lt;blockquote&gt;&lt;i&gt;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...). 
&lt;/i&gt;&lt;/blockquote&gt;

&lt;p&gt;The only difference between:&lt;code&gt;
print 0.29 * 50;;
14.5
&lt;/code&gt;

&lt;p&gt;And:&lt;code&gt;
printf "%.20f\n", 0.29 * 50;;
14.49999999999999800000
&lt;/code&gt;

&lt;p&gt;is what gets printed out; not what is calculated and stored internally.

&lt;P&gt;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.

&lt;p&gt;As for your perceived difference when gratuitously using eval:&lt;code&gt;
printf "%.20f\n",  eval eval( 0.29 ) * eval( 50 );;
14.50000000000000000000
&lt;/code&gt;

&lt;p&gt;The first thing to note is that the first two [eval]s make no difference whatsoever:&lt;code&gt;
printf "%.20f\n",  eval 0.29 * 50;;
14.50000000000000000000
&lt;/code&gt;

&lt;P&gt;And the reason for that difference is because (in this form) [eval] expects a string. So the result of the multiplication (&lt;c&gt;eval( 0.29 ) * eval( 50 )&lt;/c&gt;) is converted to a string -- using the same rules as [print] -- before being passed to the final [eval].

&lt;p&gt;You get identically different results if you do:&lt;code&gt;
$n = 0.29 * 50; printf "%.20f\n",  "$n";;
14.50000000000000000000
&lt;/code&gt;

&lt;P&gt;Because the internal (IEEE754) representation has been lost by the conversion to a string.

&lt;P&gt;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.



&lt;div class="pmsig"&gt;&lt;div class="pmsig-171588"&gt;
&lt;hr /&gt;
&lt;font size=1 &gt;
&lt;div&gt;With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'&lt;/div&gt;
&lt;div&gt;Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.&lt;/div&gt;
&lt;div&gt;"Science is about questioning the status quo. Questioning authority". &lt;/div&gt;
&lt;div&gt;In the absence of evidence, opinion is indistinguishable from prejudice.
&lt;/div&gt;
&lt;/font&gt;

&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
1016160</field>
<field name="parent_node">
1016160</field>
</data>
</node>
