Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid rounding error (floating specifically) c++

Tags:

c++

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.

like image 948
CppLearner Avatar asked Aug 05 '10 23:08

CppLearner


People also ask

How do I stop my floating from rounding?

you need to include <iomanip> and use the std::setprecision manipulator. To get the level of accuracy you want you will need to use double s rather than float s.

Can floating point operations cause round off errors?

Even if some numbers can be represented exactly by floating-point numbers and such numbers are called machine numbers, performing floating-point arithmetic may lead to roundoff error in the final result.

What causes floating point rounding errors?

Because floating-point numbers have a limited number of digits, they cannot represent all real numbers accurately: when there are more digits than the format allows, the leftover ones are omitted - the number is rounded.


1 Answers

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

like image 139
Jim Lewis Avatar answered Oct 22 '22 17:10

Jim Lewis