Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double variables in c++ are showing equal even when they are not

Tags:

c++

c

I just wrote the following code in C++:

double variable1;
double variable2;
variable1=numeric_limits<double>::max()-50;
variable2=variable1;
variable1=variable1+5;
cout<<"\nVariable1==Variable2 ? "<<(variable1==variable2);

The answer to the cout statement comes out 1, even when variable2 and variable1 are not equal.Can someone help me with this? Why is this happening?

I knew the concept of imprecise floating point math but didn't think this would happen with comparing two doubles directly. Also I am getting the same resuklt when I replace variable1 with:

double variable1=(numeric_limits<double>::max()-10000000000000);

The comparison still shows them as equal. How much would I have to subtract to see them start differing?

like image 218
gandalf34 Avatar asked Dec 06 '22 20:12

gandalf34


2 Answers

The maximum value for a double is 1.7976931348623157E+308. Due to lack of precision, adding and removing small values such as 50 and 5 does not actually changes the values of the variable. Thus they stay the same.

like image 143
slaphappy Avatar answered Jan 13 '23 00:01

slaphappy


There isn't enough precision in a double to differentiate between M and M-45 where M is the largest value that can be represented by a double.

Imagine you're counting atoms to the nearest million. "123,456 million atoms" plus 1 atom is still "123,456 million atoms" because there's no space in the "millions" counting system for the 1 extra atom to make any difference.

like image 30
RichieHindle Avatar answered Jan 12 '23 22:01

RichieHindle