Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

why you do dis to me mod

Name: Anonymous 2011-01-08 22:28

-3 % 9 == 6
http://www.wolframalpha.com/input/?i=-3%259

but

//Java and C both do this
void main()
{
  printf("%d", -3%9);
}


outputs:
-3
 instead of 6


why?

Name: Anonymous 2011-01-08 22:31

(-3)%9

Name: Anonymous 2011-01-08 22:48

>>2
still -3, easiest way to go around this is


-3%9+9
//-3+9
//6

Name: Anonymous 2011-01-09 1:42

There are different ways of thinking about remainders when you deal with negative numbers, and he is probably confusing two of them. The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. In this case, -340 lies between -360 and -300, so -360 is the greatest multiple LESS than -340; we subtract 60 * -6 = -360 from -340 and get 20.

Working with a positive number like 340, the multiple we subtract is smaller in absolute value, giving us 40; but with negative numbers, we subtract a number with a LARGER absolute value, so that the mod function returns a positive value. This is not always what people expect, but it is consistent.

If you want the remainder, ignoring the sign, you have to take the absolute value before using the mod function.

Name: Anonymous 2011-01-09 4:21

0]=> racket
Welcome to Racket v5.0.2.
(modulo -3 9)
6
(remainder -3 9)
-3

Name: Anonymous 2011-01-09 4:39

>>5
I thought they were called mod and rem.

Name: Anonymous 2011-01-09 4:44

#define abs(x) { typeof(x) _x=x; (_x<0)?-_x:_x; }
#define reminder(x,y) { abs(x)%y; }

Name: Anonymous 2011-01-09 4:45

>>7
s/min/main/

Name: Anonymous 2011-01-09 6:18

This is to do with Java integer truncation.

-3 / 9 //= 0 (not -1 so it's being ceiled not floored for -ive numbers)

The % operator is defined as:

(a / b) * b + (a % b) == a

This definition is fine, but with the integer truncation above gives the "wrong" answer.

It's probably the same case for C.

Name: Anonymous 2011-01-09 19:39

#define NEGMOD(a, b) ( (b + (a % b)) % b )

void.h Quality!

Name: Anonymous 2011-01-31 19:46

<-- check em dubz

Name: Anonymous 2011-02-02 23:38

Name: Anonymous 2011-02-04 13:15


Don't change these.
Name: Email:
Entire Thread Thread List