Implemented java.lang.Math.random() properly (seeding the random number

on first use, and then using the system random number generator)
This commit is contained in:
Eric Scharff 2007-11-28 17:06:04 -07:00
parent d24b633665
commit 51c198f0f0
2 changed files with 32 additions and 1 deletions

View File

@ -136,6 +136,26 @@ Java_java_lang_Math_pow(JNIEnv*, jclass, jdouble val, jdouble exp)
return pow(val, exp);
}
extern "C" JNIEXPORT void JNICALL
Java_java_lang_Math_natRandomInitialize(JNIEnv*, jclass, jlong val)
{
#ifdef WIN32
srand(val);
#else
srand48(val);
#endif
}
extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_natRandom(JNIEnv*, jclass)
{
#ifdef WIN32
return rand();
#else
return drand48();
#endif
}
extern "C" JNIEXPORT jdouble JNICALL
Java_java_lang_Math_floor(JNIEnv*, jclass, jdouble val)
{

View File

@ -3,6 +3,7 @@ package java.lang;
public final class Math {
public static final double E = 2.718281828459045;
public static final double PI = 3.141592653589793;
private static boolean randomInitialized = false;
private Math() { }
@ -62,7 +63,17 @@ public final class Math {
return (int) Math.floor(v + 0.5);
}
public static native double random();
public static double random() {
if (randomInitialized) {
natRandomInitialize(System.currentTimeMillis());
randomInitialized = true;
}
return natRandom();
}
public static native void natRandomInitialize(long val);
public static native double natRandom();
public static native double floor(double v);