Hi R developers and users: How do "mod" and "integer division" work with negative integers on R? I mean why you obtain different results if you work on C or anywhere else and in R? I see R guarantees that `x == (x %% y) + y * ( x %/% y )', but it looks rare the individual (x %% y) and y * ( x %/% y ) results when you use negative integers, because is contradictory to what is expected, e.g. -17 mod 15 should be -2, but R shows 13 and -17 integer division 15 should be -1, but R shows -2 because the reconstruction formula should be 15*(-1)+(-2) == -17 Or am I wrong? Thank you for your help Kenneth
Kenneth Cabrera wrote:> I mean why you obtain different results if you work on C or anywhere > else and in R?Because R is not C, and they are doing different things.> -17 mod 15 should be -2, but R shows 13 and > -17 integer division 15 should be -1, but R shows -2 > because the reconstruction formula should be 15*(-1)+(-2) == -17 > Or am I wrong?R is doing "arithmetic modulo N" (which can only take values from 0 to N-1) and C is doing 'remainder when divided by N' which can be negative. These are two different (but related) things. R's %% operator is documented as "x mod y" - which means it does modulo-y arithmetic. The man page for 'fmod' in C says: "The fmod() function computes the remainder of dividing x by y". I dont have my K+R C book handy to see how they define the x % y operator, but I suspect its the same. Baz