question_id's blog

By question_id, history, 11 years ago, In English

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.

  • Vote: I like it
  • -13
  • Vote: I do not like it

»
11 years ago, hide # |
 
Vote: I like it +16 Vote: I do not like it

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.

  • »
    »
    11 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Thanks ... In some problem , they want that error tolerance is 10^-6. What does it means? Is it enough to use 1e-6 or 1e-7?

    • »
      »
      »
      10 years ago, hide # ^ |
       
      Vote: I like it +4 Vote: I do not like it

      I also want this answer

      • »
        »
        »
        »
        10 years ago, hide # ^ |
        ← Rev. 3  
        Vote: I like it +1 Vote: I do not like it

        It means in some cases answer can't be exactly correct in some problems which we use double. So system accepts answer with 10 - 6 error. For example, answer is 1.0000021 and your program prints 1.000002, so system will accept your solution if error limit is 10 - 6 (because abs(1.0000021 - 1.000002) < 10 - 6).