ahmad_mamdouh's blog

By ahmad_mamdouh, 11 years ago, In English

In most of the courses studied in the college , I was always told to take care of the double precision errors and never to compare two double(float) numbers with the equal operator .
But the problem I faced now is a bit different , let's think of this JAVA snippet of code :


double x = 2.55 ;
double y = x * 100 ;
System.out.println(y) ;

You'll be astonished with the result , you'll see " 254.99999999999997 " .
The problem will propagate if you're going to use the integer portion of the result which will yield  " 254 " instead of " 255 " .

The problem arose due to the infinite double representation inside the computer which can't be accurate as it's not terminating . However , the solution is very easy .
If you added a very small value to the resulted double ( EPS = 1e-9 ) .
you'll find that y = 255.00000000099996 so you'll get the correct result up to the accuracy you adjusted ( i.e 10^-9 accuracy ) .

Some algorithms problems will always give you wrong answer if you don't take care of such gotchas like this one : Transmigration .

Full text and comments »

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

By ahmad_mamdouh, 12 years ago, In English
My Rating didn't change despite I participated in today's contest . Please Recheck it as this is an awful bug.

Full text and comments »

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it