My understanding is that both C's double and Javascript's numbers are IEEE 754 64 bit floating point numbers. I am trying to port some code from C to Nodejs, and I am running into what appears to be a rounding error in Javascript's 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 is:
shared: 729.000000, exponent: 15.000000, prime: 1500450271.000000, pow: 8727963568087711970669458465954849888403456.000000, mod: 1488486878.000000, result: 1488486878
Interestingly, 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
In addition, when I store the power result from C in a Javascript number:
> 8727963568087711970669458465954849888403456.0
8.727963568087712e+42
Note the difference -> 8.727963568087713e+42 !== 8.727963568087712e+42, so understandably the modulo operation fails to produce the same result.
I've had a look at the source for v8's implementation of Math.pow, but the masm macros look like greek to me atm.
Any help here is appreciated.
Aucun commentaire:
Enregistrer un commentaire