[R-sig-teaching] checking even/odd in R
jones at reed.edu
Mon Dec 4 18:43:30 CET 2006
Quoting John Fox <jfox at mcmaster.ca>:
> Dear Albyn,
> I thought about rounding but was concerned that the arithmetic would still
> be performed on real numbers. This is true even if the left argument to %%
> is coerced to an integer. (round itself produces a double-precision floating
> point number, not an integer.) I'm not sure whether this is a realistic
It is easy to test.
> pi %% 2
> trunc(pi) %% 2
> round(pi) %% 2
> is.integer(round(pi) %% 2)
> round(pi) %% 2 == 1
You are indeed correct; round() yields a double rather than an integer.
However, %% seems to do the right thing anyway, and the equality test
I expect that for a sufficiently large double, finite precision will
force it to be even even :-) but that's pretty big.
> (2^65-1) %% 2
probable complete loss of accuracy in modulus
it loooks like somebody thought of this problem already!
More information about the R-sig-teaching