Palace Chan
Palace Chan

Reputation: 9213

Why is c++ giving me different answer for what looks like the same computation?

I have the following source code in a simple main:

int main(int argc, char** argv)
{
    double x = atof(argv[1]);
    double y = atof(argv[2]);

    double res = x + std::floor((y - x) * .5 * 100 + .5)*0.01;

    std::cout << res << std::endl;
}

If I run the above with 75.21 75.22 it gives me 75.22 but if i run it with 7.21 and 7.22 it gives me 7.21. Both these number differ by 0.01 so I don't understand why this is happening?

Upvotes: 0

Views: 172

Answers (4)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

When you subtract two almost identical numbers y and x, to get a number orders of magnitude smaller than both, you always lose a lot of precision (except in the unlikely case that the binary expansions of both y and x terminates no later than at the 53rd bit). That's not surprising.

In this particular case, you can see the "issue" easily without tricks by just calculating

75.22 - 75.21

and

7.22 - 7.21

(the results will be 0.0100000000000051 and 0.00999999999999979, respectively).

Upvotes: 0

user1830108
user1830108

Reputation: 193

in x = atof () can not be right

double atof ( const char * str )

Upvotes: 0

High Performance Mark
High Performance Mark

Reputation: 78364

Among the many intricacies of floating-point arithmetic is the fact that floating-point numbers are not evenly distributed along the real line between their minimum and maximum values. Close to 0 floating-point numbers, considered as points on the real number line, are denser than away from 0, and the density decreases as the (absolute) distance from 0 increases.

For the usual IEEE standard representations there are as many numbers between, say, 1(base-10) and 2(base-10) as there are between 2(base-10) and 4(base-10). There are the same number of floating-point numbers in the interval [2^i,2^i+1] for any (positive or negative) integer i such that both the end points of the interval are representable.

Considering this, it is not surprising that the precision of base-10 calculations decreases as the magnitude of the absolute values involved increase.

Upvotes: 3

Matt Kline
Matt Kline

Reputation: 10507

The short answer: floating-point values are imprecise.

The long answer: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Upvotes: 5

Related Questions