Consecutive calls of Math.random() always return same value

Nov 1, 2014 at 5:11 PM
Edited Nov 3, 2014 at 10:23 AM
E.g. Calling the custom random() function that concats 4 values returned by Math.random()
function random() {
return Math.random() + "-" + Math.random() + "-" + Math.random() + "-" + Math.random();
};
returns
0.2160154353901816-0.2160154353901816-0.2160154353901816-0.2160154353901816

Note, in this sample, the sub-strings separated by ‘-‘ are same.

In code, MathInstance.cs appears to construct a new .NET Random object without using a different seed, thus the random sequence will be determined by the default seed, which is the current system time. Refer to the MSDN page http://msdn.microsoft.com/en-us/library/system.random%28v=vs.110%29.aspx
private static JsValue Random(JsValue thisObject, JsValue[] arguments)
        {
            return new Random().NextDouble();
        }
In the short sample code, it is highly possible that Jint executes the 4 Math.random() calls in the same milliseconds interval, and returns same random value.

This problem is described in the Stack Overflow page http://stackoverflow.com/questions/4855756/random-number-generation-same-number-returned
It happens because the Random object is initialized from Environment.GetTickCount, which is a millisecond timer. So if you call the Random constructor twice within the same millisecond, you're going to get the same initial value.
Version: Jint 2.4.0
Potential fix: use a static .NET Random object in MathInstance.cs
Severity: high
Nov 1, 2014 at 9:53 PM
Are you using the new version on github/nuget ?
Nov 3, 2014 at 10:21 AM
Same with Jint 2.4.0 from the NuGet gallery
Nov 3, 2014 at 9:12 PM
Thanks, would you mind filing a bug on github?
Nov 7, 2014 at 4:50 PM