PHP Exercises: Check if two numbers are approximately equal to each other
94. Approximately Equal Number Check
Write a PHP program to check if two numbers are approximately equal to each other.
Note: Use abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.
Sample Solution:
PHP Code:
Explanation:
- Function Definition:
- The approximatelyEqual function takes three parameters:
- $number1: the first number to compare.
- $number2: the second number to compare.
- $epsilon: an optional precision threshold, defaulted to 0.001.
- Check Approximate Equality:
- The function calculates the absolute difference between $number1 and $number2 using abs($number1 - $number2).
- If this difference is less than $epsilon, the numbers are considered approximately equal.
- Return Result:
- If the numbers are approximately equal, the function returns 1 (true).
- If not, it returns 0 (false).
- Function Calls and Output:
- approximatelyEqual(10.0, 10.00001) checks if 10.0 and 10.00001 are approximately equal within 0.001. Result: 1 (true).
- approximatelyEqual(10.0, 10.01) checks if 10.0 and 10.01 are approximately equal within 0.001. Result: 0 (false).
Output:
1 0
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to compare two floating point numbers and return true if their difference is within a small epsilon value.
- Write a PHP function to determine if two numbers are nearly equal by checking if their absolute difference is less than 0.001.
- Write a PHP script to check for approximate equality between two decimal numbers using a custom tolerance.
- Write a PHP script to evaluate if two numbers are approximately equal by comparing their difference to a default epsilon value.
Go to:
PREV : Sort Collection by a Specific Key.
NEXT : Check String Starts With Substring.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.