w3resource

PHP Exercises: Check if two numbers are approximately equal to each other

PHP: Exercise-94 with Solution

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:

<?php
// Licence: https://bit.ly/2CFA5XY

// Function definition for 'approximatelyEqual' that takes two numbers and an optional epsilon value as parameters
function approximatelyEqual($number1, $number2, $epsilon = 0.001)
{
    // Check if the absolute difference between the numbers is less than the epsilon value
    if (abs($number1 - $number2) < $epsilon)
        // If approximately equal, return 1 (true)
        return 1;
    else
        // If not approximately equal, return 0 (false)
        return 0;
}

// Call 'approximatelyEqual' with two numbers and display the result using 'print_r'
print_r(approximatelyEqual(10.0, 10.00001));

// Display a newline
echo("\n");

// Call 'approximatelyEqual' with two different numbers and display the result using 'print_r'
print_r(approximatelyEqual(10.0, 10.01));

?>

Sample Output:

1
0

Flowchart:

Flowchart: Check if two numbers are approximately equal to each other.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP program to sort a collection of given arrays or objects by key.
Next: Write a PHP program to check if a given string starts with a given substring.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.