Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an incorrect output from a modulus operation with negative number

Tags:

flutter

dart

I tried this code on Dart: I get 28.5

void main() {
  double modulo = -1.5 % 30.0;
  print(modulo);
}

The same code in Javascript returns -1.5

let modulo =  -1.5 % 30;
console.log(modulo);

What is the equivalent of the javascript code above in Dart ?

like image 582
TSR Avatar asked Nov 07 '25 16:11

TSR


2 Answers

An issue was raised about this in the dart-lang repo a while ago. Apparently the % symbol in dart is an "Euclidean modulo operator rather than remainder."

An equivalent of what you are trying to do can be accomplished with

(-1.5).remainder(30.0)
like image 88
ByteMe Avatar answered Nov 10 '25 06:11

ByteMe


The documentation for num.operator % states (emphasis mine):

Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs().

...

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

Meanwhile, num.remainder says (again, emphasis mine):

The result r of this operation satisfies: this == (this ~/ other) * other + r. As a consequence the remainder r has the same sign as the divider this.

So if you use:

void main() {
  double modulo = (-1.5).remainder(30.0);
  print(modulo);
}

you'll get -1.5.

Note that both values are mathematically correct; there are two different answers that correspond to the two different ways that you can compute a negative quotient when performing integer division. You have a choice between rounding a negative quotient toward zero (also known as truncation) or toward negative infinity (flooring). remainder corresponds to a truncating division, and % corresponds to a flooring division.

like image 30
jamesdlin Avatar answered Nov 10 '25 05:11

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!