ðŸ“˜ Compare numbers approximately using Perl 6

# ðŸ“˜ Compare numbers approximately using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

Compare the two non-integer values approximately.

Comparing non-integer numbers, which are represented as floating-point numbers is often a task that requires approximate comparison.

In Perl 6, there is theÂ `=~=` operator, called theÂ approximately-equal operator, which checks if its operands are close enough to each other.

`say 1/1000 =~= 1/1001;         # Falsesay 1/1E20 =~= 1 / (1E20 + 1); # True`

The result of the approximate comparison isÂ `True` if the difference is less than the value set in theÂ `\$*TOLERANCE` constant, which is equal toÂ `1E-15`.

Notice that in Perl 6, a number in a scientific notation is a floating-point number, while other representations, such asÂ `0.5` orÂ `1/2`, orÂ `<1/2>`, or evenÂ `Â½`, are the values of theÂ `Rat` type (Rat stands forÂ rational).

Rational numbers are stored as two integer values, the numerator and the denominator. Computations with such numbers, therefore, do not loose accuracy. Compare the results of the following classical example, with a similar program in other languages:

`say 0.1 + 0.2 - 0.3; # 0`

Perl 6 prints an exact zero, even if you try to print the result with many digits after the decimal point:

`'%.20f'.printf(0.1 + 0.2 - 0.3);Â # 0.00000000000000000000`

This is very nice of Perl 6, isnâ€™t it?