integer division towards -infinity

S

Sidney Cadot

Hi all,

As I understand it, the rounding direction of signed integer division
in C is unspecified in C89/C94, and specified to be 'towards-zero' in
C99.

I need division 'towards -infinity' (with a 'mod' operation to match),
i.e. for x and y I need to obtain D and M such that

(1) D*abs(y)+M == x
(2) 0 <= M<abs(y)

For any signed x,y (y!=0).

Is there a canonical way of doing this that is guaranteed to work in
line with all C specifications?

Best regards,

Sidney Cadot
The Netherlands
 
R

Robert W Hand

Hi all,

As I understand it, the rounding direction of signed integer division
in C is unspecified in C89/C94, and specified to be 'towards-zero' in
C99.

I need division 'towards -infinity' (with a 'mod' operation to match),
i.e. for x and y I need to obtain D and M such that

(1) D*abs(y)+M == x
(2) 0 <= M<abs(y)

For any signed x,y (y!=0).

Is there a canonical way of doing this that is guaranteed to work in
line with all C specifications?

Did you think of using div_t div(int, int)? It does not round to
minus infinity, but at least it rounds the same in both standards,
IIRC.

Best wishes,

Bob
 
J

Jarno A Wuolijoki

Indeed this can be used to solve my problem. However I thought of an
alternative this afternoon that is a bit terser:

div_to_minus_infinity = a/b-(a%b<0);
mod_to_minus_infinity = a%b+b*(a%b<0);

Negative b, round to zero:

div: -8/-5 - (-8%-5<0) == 1 - (-3<0) == 0
mod: -8%-5 + -5*(-8%-5<0) == -3 + -5*(-3<0) == -8

Fixed ones: (i think)

div: a/b - (a%b<0 ? (b<0 ? -1 : 1) : 0)
mod: a%b + (a%b<0 ? (b<0 ? -b : b) : 0)
 
G

Glen Herrmannsfeldt

Sidney Cadot said:
Hi Bob,


Indeed this can be used to solve my problem. However I thought of an
alternative this afternoon that is a bit terser:

div_to_minus_infinity = a/b-(a%b<0);

This only assumes that the div and mod operators use equivalent
rounding rules, and works with both round-to-zero and
round-to-minus-infinity rules. In fact, it should even work with a
hypothetical round-to-positive-infinity implementation. I think it's
quite nifty :)

Mod-to-minus-infinity would look like

mod_to_minus_infinity = a%b+b*(a%b<0);

I usually use (a%b+b)%b for the mod case. I never needed the divide case,
so I never tried that one.

-- glen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top