I understand that both C doubleand Javascript numbers are 64-bit IEEE 754 floating-point numbers. I am trying to port some code from C to Nodejs, and I am facing what seems to be a rounding error in Javascript Math.pow().
Here is my C program:
#include "stdio.h"
#include "math.h"
int main(int argc, char *argv[]) {
double shared = 729;
double exponent = 15;
double prime = 1500450271;
double power = pow(shared, exponent);
double mod = fmod(power, prime);
int intResult = (int) mod;
printf("shared: %lf, exponent: %lf, prime: %lf, pow: %lf, mod: %lf, result: %i\n",
shared, exponent, prime, power, mod, intResult);
}
The output of which:
shared: 729.000000, exponent: 15.000000, prime: 1500450271.000000, pow: 8727963568087711970669458465954849888403456.000000, mod: 1488486878.000000, result: 1488486878
I wonder when I try to perform this calculation in Javascript (tested in node, Chrome, Firefox)
I get the following result:
> Math.pow( 729, 15)
8.727963568087713e+42
> Math.pow( 729, 15 ) % 1500450271;
93655693
Also, when I save the power result from C in a Javascript number:
> 8727963568087711970669458465954849888403456.0
8.727963568087712e+42
Note the difference 8.727963568087713e+42 !== 8.727963568087712e+42-> so it’s clear that the modulo operation does not give the same result.
I looked at the source for the v8 implementation of Math.pow, but the masm macros look like Greek atm to me.
.