On May 13, 7:16 am, Avi <avner-moshkov...@[EMAIL PROTECTED]
> wrote:
> I need to implement the following calculation:
> f =3D (a*b) + (c*d)
> where a,b,c,d are given double values and f is a double
> variable for the result
> I found out that using two different implementations gives two
> different results:
> 1) In the first implementation I compute the entire equation in memory
You mean in CPU and registers. Variables are in memory.
> 2) In the second implementation I store intermediate to
> variables, and then load them to compute the final result.
> The results differ by a tiny amount (1E-15). I suspect that
> the reason for the difference is from round off errors of the
> compiler.
The C++ standard allows a compiler to use extended precision for
intermediate results, only "forcing" the result to the final
precision when it is assigned to a variable.
> Nonetheless, I need to know the reason for the difference as I
> need to have an absolute reference for optimization work.
> The two ways are as follows:
> 1)
> Calculating two double values and then summing them to a
> single double value
> double f1 =3D (a*b) + (c*d)
All calculations may be done in extended precision.
> 2)
> Calculating two double values and storing them to two double variables
> Summing the two double variables to a single double value
> double e1 =3D (a*b);
This forces the result to double.
> double e2 =3D (c*d);
As does this as well.
> double f2 =3D e1 + e2;
> The difference is calculated as follows:
> double diff =3D f2-f1;
> I expect the difference to be exactly 0 but instead, I get a
> tiny value. Could someone explain the reason for differences
> in the result?
It's very implementation dependent.
> I'm compiling with gcc
More to the point, you're compiling on a machine which uses
extended precision in its floating point unit, and its floating
point registers. (An Intel, perhaps.)
The reason for this freedom is speed. Forcing the results of
each operation to be rounded to double can be done, but would
slow things down considerably (at least on Intel). And for the
most part, increased precision is not considered a defect.
--
James Kanze (GABI Software) email:james.kanze@[EMAIL PROTECTED]
en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34


|