Zalgorithm

Difference between how Python and Java handle the modulus function

The problem: wanting a positive measure of degrees in radians for some value that may be either positive or negative in any range. Test value: negative_degrees = -TWO_PI * 2 + 0.1

Python:

In [80]: negative_degrees = np.pi * -2 + 0.1

In [81]: negative_degrees % 2*np.pi
Out[81]: 5.707691691898607

Java:

void setup() {
  size(300, 300);
  float negativeDegrees = -TWO_PI + 0.1;
  println(negativeDegrees % TWO_PI);
}
// -6.1831856

Python and Java handle the modulus operator differently. This affects the results of performing the modulus operation on negative numbers. Python uses floored division:

import math

a % b = a - b * math.floor(a / b)

Java uses truncated division:

a % b = a - b * int(a / b);  // the sign is preserved (using `int` for truncation in this example)

The solution for my specific case:

float normalizeTheta(float theta) {
  float normalizedTheta = theta % TWO_PI;
  if (normalizedTheta < 0) normalizedTheta += TWO_PI;
  return normalizedTheta;
}

Longer test with Java (Processing):

void setup() {
  size(300, 300);
  // the desired result is 0.1 (the positive direction)
  float negativeDegrees = -TWO_PI + 0.1;
  println(negativeDegrees % TWO_PI);
  float mod = negativeDegrees % TWO_PI;
  println("Original mod:", mod);
  if (mod < 0) mod += TWO_PI;
  println("Normalized mod:", mod);

  float modImplTest = negativeDegrees - int(negativeDegrees / TWO_PI);
  println("modImplTest:", modImplTest);
  if (modImplTest < 0) modImplTest += TWO_PI;
  println("Normalized modImplTest:", modImplTest);
  println(mod);
}
// -6.1831856
// Original mod: -6.1831856
// Normalized mod: 0.099999905
// modImplTest: -6.1831856
// Normalized modImplTest: 0.099999905
// 0.099999905