I'm trying to implement a JS function in Java. I copied the code over almost verbatim, since both use 64 bit floating point for float/Double types and the same operator precedence for math operators(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html and https://msdn.microsoft.com/en-us/library/ie/z3ks45k7(v=vs.94).aspx). However, I see a difference in results between the two while debugging. Specifically, this line in JavaScript:
var mu = M / (this.a * (1 - esq * (1 / 4 + esq * (3 / 64 + 5 * esq / 256))));
and its Java equivalent:
Double mu = M / (a * (1 - esq * (1 / 4 + esq * (3 / 64 + 5 * esq / 256))));
with the following values:
M=4373246.298519407, esq=0.006694379989312105, a=6378137.0
The results are 0.6856620239020387 and 0.6868129133457879 respectively. Could someone explain this and give the correct Java code? This inaccuracy is translating to large difference in the final output of the function
The code is not quite equivalent between Javascript and Java.
In Javascript, all numbers are doubles, so floating-point math will take place. However, in Java, integer division will take place, so that for example 1/4
will yield 0
, not 0.25
.
As written, in Java I get 0.6856620239020387
.
Changing the Java numbers to use double
literals:
Double mu = M / (a * (1.0 - esq * (1.0 / 4.0 + esq * (3.0 / 64.0 + 5.0 * esq / 256.0))));
Now, I get the other number: 0.6868129133457879
, the value I get in Javascript.