Approximate equality between two real numbers is determined by checking whether their absolute difference is within a specified tolerance (epsilon).
- Uses a tolerance (epsilon) to handle floating-point precision issues.
- Calculates the absolute difference between the two numbers.
- Returns true if the difference is less than epsilon; otherwise, returns `false.
The following examples illustrate approximate number comparison using different values and tolerance levels.
Example 1: Compares two decimal numbers using a larger tolerance value.
const isApprox = (num1, num2, epsilon) => {
// Calculate the absolute difference
// and compare it with epsilon
return Math.abs(num1 - num2) < epsilon;
};
console.log(isApprox(10.3, 10.1, 0.5));
Output
true
Example 2: Compares a mathematical constant with its approximate decimal value.
const isApprox = (num1, num2, epsilon) => {
// Calculate the absolute difference
// and compare it with epsilon
return Math.abs(num1 - num2) < epsilon;
};
console.log(isApprox(Math.PI / 2.0, 1.5708, 0.004));
Output
true
Example 3: Compares two numbers whose difference exceeds the specified tolerance.
const isApprox = (num1, num2, epsilon) => {
// Calculate the absolute difference
// and compare it with epsilon
return Math.abs(num1 - num2) < epsilon;
};
console.log(isApprox(0.003, 0.03, 0.004));
Output
false