Guru Prasad
Guru Prasad

Reputation: 4233

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

Upvotes: 5

Views: 2339

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320719

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.

Upvotes: 10

Bernd Elkemann
Bernd Elkemann

Reputation: 23560

Aside from the reference to (1991, PDF) What Every Computer Scientist Should Know About Floating-Point Arithmetic

The short answer is, that because float has limited storage (like the other primitives too) the engineers had to make a choice: which numbers to store with which precision. For the floating point formats they decided to store numbers of small magnitude precisely (some decimal digits), but numbers of large magnitude very imprecisely, in fact starting with +-16,777,217 the representable numbers are becoming so thin that not even all integers are represented which is the thing you noticed.

Upvotes: 1

Related Questions