goe goe - 1 month ago 16
Java Question

Why does modulo operation gives different results in Java VS Perl?

I run this in Java 7 and I get:

double remainder1 = 1 % 1000;
double remainder2 = 0.01 % 1000;
double remainder3 = -1 % 1000;

System.out.println("START: "+remainder1+" | "+remainder2+" | "+remainder3);
>>>START: 1.0 | 0.01 | -1.0


But when I run the same operations in Perl 5.8.8 I get different results for two out of three:

my $remainder1 = 1 % 1000;
my $remainder2 = 0.01 % 1000;
my $remainder3 = -1 % 1000;
print "START: $remainder1 | $remainder2 | $remainder3";
>>>START: 1 | 0 | 999


Why is there such a difference in the last two calculations?
How can I get perl to match java results?

mob mob
Answer

Use the POSIX::fmod function.

This is identical to the C function fmod().

$r = fmod($x, $y);

It returns the remainder $r = $x - $n*$y, where $n = trunc($x/$y). The $r has the same sign as $x and magnitude (absolute value) less than the magnitude of $y.

use POSIX 'fmod';

$m1 = fmod(1, 1000);     # 1
$m2 = fmod(0.01, 1000);  # 0.01
$m3 = fmod(-1, 1000);    # -1