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.
[100000000000000.01,100000000000000.011,100.01,100.011,10000000000000.001/10000.0,1000000000.0000001000,0.001,0.0010000001,0.000000000000000000000101,0.0, sqrt(2) * sqrt(2),2.0,-sqrt(2) * sqrt(2),-2.0, sqrt(-2) * sqrt(-2),-2.0, cbrt(3)**3,3, cbrt(-3)**3,-3,100000000000000003.0,100000000000000004.0,3.14159265358979323846,3.14159265358979324].each_slice(2, {|a,b| say ("#{a} ≅ #{b}: ", a ≅ b)})
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.01var b =100000000000000.011# Rounding at 2 and 3 decimal places, respectivelysay (round(a,-2) == round(b,-2)) # truesay (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/7var b =Num.pisay ("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) # truesay (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)}