What is the approx() method in Euphoria?

Overview

Approximation is a very relevant arithmetic operation. By approximating, we either return a float value to the next lower or higher integer value. There is a special function in Euphoria to check the approximate equality of two values.

What is the approx() method?

The approx() method is a built-in method that checks the approximate equality of two values. This means that the function will check using a default or specified reference value. This determines how approximately close to being equal two values are.

Let’s say value A is 0.01 approximately equal to value B. We use the approx() method approx(A,B,0.01). This will return 1 which means it is true. But it returns 0 if that is not true.

Syntax

approx(A, B, ref)
  • A: One of the integer value that will be considered for the equality check.
  • B: Another value to be checked.
  • ref: This atom value defines the allowable inequality range based on which the equality is checked. The default value of 0.005 will be used if not provided.

Return value

This function returns an integer which can be:

  • 1: This is returned when A > ( B + ref). And it entails that A is definitely greater than B.
  • -1: This value is returned when A < (B - ref). This means that P is surely less than B.
  • 0: This is returned when A >= (B - ref) and A <= (B + ref). This means that A and B are approximately equal.
--include math package file
include std/math.e
--
? approx(10,10.002333)
--> return is 0, 10 and 10.002333 have a difference less than 0.005
? approx(84, 84.001)
--> 0 is returned. 10 and 10.001 are within 0.005 of each other
? approx(20, {20.001,19.999, 19.98, 20.04})
--> {0,0,1,-1} is returned after approximate equality of
--20 with all sequence elements where checked
? approx({62.001, 61.999, 61.98, 62.04}, 10)
--> {1,1,1,1}
? approx({10.001,{9.999, 10.01}, 9.98, 10.04}, {10.01,9.99, 9.8, 10.4})
--> {-1,{1,1},1,-1}
? approx(55,70, 10)
--> returns -1 because 55 < (70 - 10) and 70 and 55 are not within 10 of each other.

Explanation

  • Line 2: We include the math.e standard library file.
  • Lines 5–21: We use the approx() method to check for the equality proximity of different values.

Free Resources