[R-sig-teaching] checking even/odd in R
Albyn Jones
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
> worry.
>
> Regards,
> John
It is easy to test.
> pi
[1] 3.141593
> pi %% 2
[1] 1.141593
> trunc(pi) %% 2
[1] 1
> round(pi) %% 2
[1] 1
> is.integer(round(pi) %% 2)
[1] FALSE
> round(pi) %% 2 == 1
[1] TRUE
You are indeed correct; round() yields a double rather than an integer.
However, %% seems to do the right thing anyway, and the equality test
works....
I expect that for a sufficiently large double, finite precision will
eventually
force it to be even even :-) but that's pretty big.
> (2^65-1) %% 2
[1] 0
Warning message:
probable complete loss of accuracy in modulus
it loooks like somebody thought of this problem already!
albyn
More information about the R-sig-teaching
mailing list