tags:

views:

79

answers:

6

http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/ I have been about this lately to review C++.

In general computing class professors tend not to cover these small things, although we knew what rounding errors meant.

Can someone please help me with how to avoid rounding error?

The tutorial shows a sample code

#include <iomanip>
int main()
{
    using namespace std;
    cout << setprecision(17);
    double dValue = 0.1;
    cout << dValue << endl;
}

This outputs

0.10000000000000001

By default float is kept 6-digits of precisions. Therefore, when we override the default, and asks for more (n this case, 17!!), we may encounter truncation (as explained by the tutorial as well). For double, the highest is 16.

In general, how do good C++ programmers avoid rounding error? Do you guys always look at the binary representation of the number?

Thank you.

+3  A: 

The canonical advice for this topic is to read "What Every Computer Scientist Should Know About Floating-Point Arithmetic", by David Goldberg.

Jim Lewis
A: 

You can always use arbitrary precision number. Why do you need to avoid this rounding error? there are some more specific solutions

Dani
A: 

Most floating point output routines look to see if the answer is very close to being even when represented in base 10 and round the answer to actually be even on output. By setting the precision in this way you are short-circuiting this process.

This rounding is done because almost no answer that comes out even in base 10 will be even (i.e. end in an infinite string of trailing 0s) in base 2, which is the base in which the number is represented internally. But, of course, the general goal of an output routine is to present the number in a fashion useful for a human being, and most human beings in the world today read numbers in base 10.

Omnifarious
A: 

Short version - you can't really avoid rounding and other representation errors when you're trying to represent base 10 numbers in base 2 (ie, using a float or a double to represent a decimal number). You pretty much either have to work out how many significant digits you actually have or you have to switch to a (slower) arbitrary precision library.

Timo Geusch
A: 

In other words, to minimize rounding errors, it can be helpful to keep numbers in decimal fixed-point (and actually work with integers).

#include <iostream>
#include <iomanip>
int main() {
  using namespace std;
  cout << setprecision(17);

  double v1=1, v1D=10; 
  cout << v1/v1D << endl;

  double v2=3, v2D=1000; 
  cout << v2/v2D << endl;

  // v1/v1D + v2/v2D = (v1*v2D+v2*v1D)/(v1D*v2D)
  cout << (v1*v2D+v2*v1D)/(v1D*v2D) << endl;
}
Shelwien
+1  A: 

You might want to check out the GNU Multiple Precision Arithmetic Library.

andand