Approximate Number Equality

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28135{{"`Approximate Number Equality`"}} javascript/data_types -.-> lab-28135{{"`Approximate Number Equality`"}} javascript/arith_ops -.-> lab-28135{{"`Approximate Number Equality`"}} javascript/comp_ops -.-> lab-28135{{"`Approximate Number Equality`"}} end

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 to epsilon.
  • If you don't provide a third argument, epsilon, the function will use a default value of 0.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.

Other JavaScript Tutorials you may like