PDA

View Full Version : double precision or what?



mickey
17th February 2007, 19:13
I coded this:


setInput(double* d) {
cout << " *d0 " << d[0] << " " << "*d1 " << d[1] << endl;
for (int i=0; i < _num_input; ++i)
_input[i] = d[i];
}

main () {
double input[2] = {4.50, 3.10};
double sum=0;
sum = input[0] + input[1];
for (uint i=0; i < 2; i++)
setInput (input);
cout << "input[0,1] " << input[0] << " " << input[1] << " " << sum << endl;
}

Output is:


*d0 4.5 *d1 3.1000000000000001 //why this '1' at the end???
input[0,1] 4.5 3.1000000000000001 7.5999999999999996

what's that '1' ???? why does it appear only after setInput() call??
thanks

jacek
17th February 2007, 19:33
Some decimal values have no accurate representation, because of limited number of bits on which a double value is encoded. That's why floating point variables are not recommended for applications where accuracy is important (like counting money).

wysota
17th February 2007, 19:52
As far as I remember usually floating point numbers are represented using powers of two, so any floating point number that can't be composed of powers of two (watch the finite length) will not be able to be represented. Maybe 3.10 is one of them :)

I think you may read a bit about it here: http://en.wikipedia.org/wiki/Floating_point (I haven't read it, so I can't guarantee, but search for "mantissa" or "significand")

Edit: You may jump directly here as well: http://en.wikipedia.org/wiki/Double_precision

mickey
20th February 2007, 07:17
ok, but then what do I have to do if I need that high precision in C++? nothing?

wysota
20th February 2007, 11:47
Just round up the value... Do you really need more than 10 digits after the decimal point? You needn't worry about the result as long as it doesn't change the significant digits.

jacek
20th February 2007, 12:46
what do I have to do if I need that high precision in C++? nothing?
Write a high-precision number class or use some library.

mickey
20th February 2007, 17:18
the problem isn't only that 3.00000000001 but others too. And with operations error is propagating (increase)...Any hints about library?
thankks

wysota
20th February 2007, 20:01
the problem isn't only that 3.00000000001 but others too. And with operations error is propagating (increase)...

As long as it keeps under the number of significant digits you need, you have nothing to worry about.

As for the lib, try this one: http://www.nongnu.org/hpalib

Or this one: http://freshmeat.net/projects/ccmath/

In any case, google is your friend.