Блог пользователя question_id

Автор question_id, история, 11 лет назад, По-английски

Hi! I've seen many codes where 1e-11 (like this) is used to compare two double numbers. Why we use this? what it we do not use this?

Thanks in advance.

  • Проголосовать: нравится
  • -13
  • Проголосовать: не нравится

»
11 лет назад, скрыть # |
 
Проголосовать: нравится +16 Проголосовать: не нравится

Doubles can only store a certain amount of digits. If you have a decimal with an unlimited amount of digits(eg. 1/3 or sqrt 2), then the computer can't possibly store all the digits. So you can get a lot of rounding errors with doubles. If you use == for comparing doubles, like so...

double d1 = blahblahblah;
double d2 = asdfjkl;
if(d1==d2){
   ...
}

Then you can run into a lot of issues, even when d1 and d2 should be equal. The safer way is to create a tolerance value epsilon. You can imagine it like an error margin: for 2 doubles to be equal, they must have an error margin of epsilon or less:

double EPS = 1e-9; //I usually use 1e-9, just to be safe on rounding errors
double d1 = blahblahblah;
double d2 = asdfjkl;
if( abs(d1-d2)<EPS){
   ...
}

This type of comparison will save you on a lot of problems.