Introduction
In this lab, we will explore how to implement a function in JavaScript that checks if two numbers are approximately equal to each other. We will use the Math.abs() method to compare the absolute difference between the two values to a specified or default epsilon value. This lab will help us understand how to handle floating-point numbers with precision in JavaScript.
Checking for Approximate Number Equality in JavaScript
To practice coding, open the Terminal/SSH and type node. This code checks if two numbers are approximately equal to each other. To do this:
- Use the
Math.abs()method to compare the absolute difference of the two values toepsilon. - If you don't provide a third argument,
epsilon, the function will use a default value of0.001.
Here's the code:
const approximatelyEqual = (v1, v2, epsilon = 0.001) =>
Math.abs(v1 - v2) < epsilon;
To test the function, you can call it with two numbers as arguments, like this:
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
This will return true because Math.PI / 2.0 is approximately equal to 1.5708 with an epsilon of 0.001.
Summary
Congratulations! You have completed the Approximate Number Equality lab. You can practice more labs in LabEx to improve your skills.