I wrote some Java code to generate pseudo-random numbers but I'm running into what I think are rounding problems getting it to match up with the same code in Ruby. Here's what I have in Java:
public class randTest {
private final static Double A = Math.pow(5,13);
private final static Integer S = 314159265;
private final static Double minVal = Math.pow(2, -46);
private final static Double maxVal = Math.pow(2, 46);
private final static Double newMax = 10.0;
private static Double r(Integer k) {
Double powS = Math.pow(A, k) * S;
Double xk = powS % maxVal.intValue();
Double result = minVal * xk;
System.out.println("k = " + k + ", pows = " + powS + ", xk = " + xk + ", result = " + result);
return result;
}
}
And the same thing in Ruby (my working reference implementation):
A = 5 ** 13
S = 314159265
MIN_VAL = 2 ** -46
MAX_VAL = 2 ** 46
NEW_MAX = 10
def r(k) # was generate_random
powS = (A ** k) * S
xk = powS % MAX_VAL
result = MIN_VAL * xk
puts "k = #{k}, pows = #{powS}, xk = #{xk}, result = #{result}"
return result
end
For some reason, the output is vastly different (but the Ruby one is correct). Here's me calling r(4):
Java:
k = 4, pows = 6.9757369880463215E44, xk = 1.512592341E9, result = 2.1495230001278287E-5
Ruby:
k = 4, pows = 697573698804632158498861826956272125244140625, xk = 55279057169489, result = 0.785562650228954
Any idea as to why powS
would be computed correctly in both but not xk
? Note that on the Java version I needed to use maxVal.intValue()
instead of maxVal
, otherwise it returns zero. I've also tried replacing the Double
s with BigDecimal
s to no avail as well.