Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird C++ float bug

#include <iostream>
using namespace std;

int main()
{
    cout.precision(32);

    float val = 268433072;
    float add = 13.5;

    cout << "result =" << (val + add) << endl;
}

I'm compiling the above program with standard g++ main.cc
and running it with ./a.out

The ouput I receive however, is,
result =268433088

Clearly, this is not the correct answer..Why is this happening?

EDIT: This does not occur when using double in place of float

like image 916
Guru Prasad Avatar asked Jul 05 '13 18:07

Guru Prasad


People also ask

What is a floating C?

A "floating-point constant" is a decimal number that represents a signed real number. The representation of a signed real number includes an integer portion, a fractional portion, and an exponent. Use floating-point constants to represent floating-point values that can't be changed.

Is floating math broken?

(1) Floating point numbers do not have error. Every floating point value is exactly what it is. Most (but not all) floating point operations give inexact results. For example, there is no binary floating point value that is exactly equal to 1.0/10.0.

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.

Can float type in python3 can represent decimal 0.1 without error?

Some values cannot be exactly represented in a float data type. For instance, storing the 0.1 value in float (which is a binary floating point value) variable we get only an approximation of the value. Similarly, the 1/3 value cannot be represented exactly in decimal floating point type.


1 Answers

You can reproduce your "float bug" with an even simpler piece of code

#include <iostream>
using namespace std;

int main()
{
    cout.precision(32);
    float val = 2684330722;
    cout << "result =" << val << endl;
}

The output

result =2684330752

As you can see the output does not match the value val was initialized with.

As it has been stated many times, floating-point types have limited precision. Your code sample simply exceeded that precision, so the result got rounded. There's no "bug" here.

like image 91
AnT Avatar answered Oct 15 '22 13:10

AnT