blueman378 Posted August 17, 2009 Share Posted August 17, 2009 hi guys, well as we all know floating point math is not exact, so i need to create an if statement to check equality of a number within a given error range eg we are looking for the equality of .99 with an error margin of .0001 so i need to find out if the difference between a and b is less than .0001 what do i need for this? Link to comment https://forums.phpfreaks.com/topic/170592-if-and-relative-equality/ Share on other sites More sharing options...
Simon Mayer Posted August 17, 2009 Share Posted August 17, 2009 How about the following? $margin = 0.0001 if(($a - $b < $margin) && ($b - $a < $margin)) { echo "numbers are almost the same"; } else { echo "numbers are not within the specified margin."; } Link to comment https://forums.phpfreaks.com/topic/170592-if-and-relative-equality/#findComment-899839 Share on other sites More sharing options...
ignace Posted August 17, 2009 Share Posted August 17, 2009 hi guys, well as we all know floating point math is not exact, so i need to create an if statement to check equality of a number within a given error range eg we are looking for the equality of .99 with an error margin of .0001 so i need to find out if the difference between a and b is less than .0001 what do i need for this? Like you already pointed out floating points in PHP are not exact and the manual tells you to use the arbitrary precision math functions as they do what their name says. http://www.php.net/manual/en/ref.bc.php Link to comment https://forums.phpfreaks.com/topic/170592-if-and-relative-equality/#findComment-899869 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.