PHP Numbers Comparing Floating-Point Numbers - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Numbers Comparing Floating-Point Numbers - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, May 8, 2019

PHP Numbers Comparing Floating-Point Numbers

PHP Numbers




Comparing Floating-Point Numbers


Problem

You want to check whether two floating-point numbers are equal.

Solution

Use a small delta value, and check if the numbers have a difference smaller than that
delta:

          $delta = 0.00001;

          $a = 1.00000001;
          $b = 1.00000000;

          if (abs($a - $b) < $delta) {
              print '$a and $b are equal enough.';
          }

Discussion

Floating-point numbers are represented in binary form with only a finite number of bits for the mantissa and the exponent. You get overflows when you exceed those bits. As a result, sometimes PHP (just like some other languages) doesn’t believe that two equal numbers are actually equal because they may differ toward the very end.

To avoid this problem, instead of checking if $a == $b, make sure the first number is within a very small amount ($delta) of the second one. The size of your delta should be the smallest amount of difference you care about between two numbers. Then use abs() to get the absolute value of the difference.

No comments:

Post a Comment

Post Top Ad