Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

div/mod behaviour #90

Open
konsumlamm opened this issue Jan 25, 2022 · 2 comments
Open

div/mod behaviour #90

konsumlamm opened this issue Jan 25, 2022 · 2 comments

Comments

@konsumlamm
Copy link
Contributor

The behaviour of div and mod is currently inconsistent with the respective operators for ints. For example:

import bigints

func divmod(a, b: int): tuple[q, r: int] =
    (q: a div b, r: a mod b)

echo "int:"
echo "  divmod(1, 2): ", divmod(1, 2)
echo "  divmod(1, -2): ", divmod(1, -2)
echo "  divmod(-1, 2): ", divmod(-1, 2)
echo "  divmod(-1, -2): ", divmod(-1, -2)
echo "BigInt:"
echo "  divmod(1, 2): ", divmod(1'bi, 2'bi)
echo "  divmod(1, -2): ", divmod(1'bi, -2'bi)
echo "  divmod(-1, 2): ", divmod(-1'bi, 2'bi)
echo "  divmod(-1, -2): ", divmod(-1'bi, -2'bi)

prints the following:

int:
  divmod(1, 2): (q: 0, r: 1)
  divmod(1, -2): (q: 0, r: 1)
  divmod(-1, 2): (q: 0, r: -1)
  divmod(-1, -2): (q: 0, r: -1)
BigInt:
  divmod(1, 2): (q: 0, r: 1)
  divmod(1, -2): (q: -1, r: -1)
  divmod(-1, 2): (q: -1, r: 1)
  divmod(-1, -2): (q: 0, r: -1)

For ints, division rounds towards 0 and the sign of a mod b is the sign of a. Meanwhile, for BigInts, division rounds towards negative infinity and the sign of a mod b is the sign of b.

I suggest we change the behavior of BigInts to match that of ints.

@def- since you implemented this, did you have a specific reason for implementing it this way?

@MichalMarsalek
Copy link

I think that generaly the motivation to implement it this way is that it doesn't break modular arithmetic. Meaning that if M divides (a-b) then a mod M == b mod M. If one does any sort of math with the integers, the other way (which is usually called remainder) gets in the way.
I think that it is really unfortunate that mod for ints means remainder rather than modulus, but that is to stay.
The ideal state would be there where two operators: rem implementing a remainder and mod implementing a modulo. For both ints and BigInts.

@rotu
Copy link
Contributor

rotu commented Oct 5, 2022

@MichalMarsalek if that’s the case, then shouldn’t the modulo always be positive? After all, $$\mathbb Zn+r = \mathbb Z(-n)+r$$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants