[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [sc-users] Problems with "real" numbers




Am 30.12.2015 um 23:51 schrieb TomD <tomdiscus@xxxxxx>:

(x - 0.3).abs < 1e-4    // 1e-4 = 1 * (10 ** -4) = 0.0001

-> true/

*(x - 0.3).abs is the same as x - 0.3...

Not in general, if you make a test if a number x
is near 0.3, you cannot assume that x is larger:
e.g. 0.29 - 0.3 < 1e-4 gives true,
but it doesn't say, that 0.29 is in a "0.0001-environment" of 0.3:
in fact it is not, as the "distance" is 0.01

If you look at the source code of equalWithPrecision,
you see that it does exactly this kind of check
(absdif is another method for taking the absolut value of the difference):

equalWithPrecision { arg that, precision=0.0001;
^absdif(this, that) < precision
}


*Ok interesting method thanks, I might replace my choice with this but it's
a little tricky because of the need to define a degree of precision...


Indeed it is problematic to define a general threshold for all magnitudes of
possible numbers.

E.g. the default precision 0.0001 fails here:

((0.1 + 0.1 + 0.1) * 1e20).equalWithPrecision(0.3 * 1e20)

--> false


I am not aware if something exists already in SC (does it maybe ?),
but a equality check with relative precision could be easily defined:

// Add a sc-file to the Extensions folder and recompile

+SimpleNumber {
equalWithRelativePrecision { arg that, relativePrecision = 0.0001;
^absdif(this, that) < (this * relativePrecision).abs
}
}


Then we can compare with a relative precision default of 0.0001:

((0.1 + 0.1 + 0.1) * 1e20).equalWithRelativePrecision(0.3 * 1e20)

--> true



Greetings

Daniel

-----------------------------
www.daniel-mayer.at
-----------------------------