Get Website Lowest price!

Wordpress Experts!

×

php up to date

PHP Facts You May Not Know

Floating Point Imprecision


Let’s look at this very small snippet:
<?php
     echo (int) ((0.1 + 0.7) * 10);



What do you think will be the result? If you guessed 8, you’d be wrong… I’m sorry, you lost the prize! This code will actually print 7! For those who have a Zend Certification, this example is already known. Infact, you can find it in Zend PHP 5 Certification Study Guide.



Now let’s see why this happens. The first operation executed is:
0.1 + 0.7 // result is 0.79999999999
The result of the arithmetic expression is stored internally as 0.7999999, not 0.8 due to the precision issue, and this is where the problem starts.
The second operation executed is:
0.79999999 * 10 = 7.999999999
This operation works well but preserves the error.
The third and last operation executed is:
(int) 7.9999999 // result is 7
The expression makes use of an explicit cast. When a value is convert to int, PHP truncates the decimal portion of the number which makes the result 7.

There are two interesting things to note here:


  • If you cast the number to float instead of int, or if you don’t cast at all, you’ll get 8 as result as you expected.
  • Although the CPU doesn’t know, and we actually we got this error due to its imprecisions, it’s working accordingly to the mathematics paradox that asserts 0.999… is equal to 1.
SHARE

blogger

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment