Two values can be compared for approximate equality by using the built-in operator ≅, available in ASCII as =~=, which does approximate comparison by rounding both operands at (PREC>>2)-1 decimals. However, by default, Sidef uses a floating-point precision of 192 bits.
The Number n.round(-k) can be used for rounding the number n to k decimal places. A positive argument can be used for rounding before the decimal point.
var a = 100000000000000.01
var b = 100000000000000.011
# Rounding at 2 and 3 decimal places, respectively
say (round(a, -2) == round(b, -2)) # true
say (round(a, -3) == round(b, -3)) # false
There is also the built-in approx_cmp(a, b, k) method, which is equivalent with a.round(k) <=> b.round(k).
var a = 22/7
var b = Num.pi
say ("22/7 ≅ π at 2 decimals: ", approx_cmp(a, b, -2) == 0)
say ("22/7 ≅ π at 3 decimals: ", approx_cmp(a, b, -3) == 0)
Output:
22/7 ≅ π at 2 decimals: true
22/7 ≅ π at 3 decimals: false
Additionally, the rat_approx method can be used for computing a very good rational approximation to a given real value:
say (1.33333333.rat_approx == 4/3) # true
say (zeta(-5).rat_approx == -1/252) # true
Rational approximations illustrated for substrings of PI:
for k in (3..19) {
var r = Str(Num.pi).first(k)
say ("rat_approx(#{r}) = ", Num(r).rat_approx.as_frac)
}