From dc5bf4275b6d40aefac038d57b3aea62a8be3d12 Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Tue, 20 Oct 2015 11:55:57 +0200 Subject: JS: Math.random(): fix range to not include 1.0. [15.8.2.14] specifies that the Math.random() returns a number greator or equal to 0, but less than 1. Libc however defines it to be less than or equal to 1, so we have to divide the returned value by RAND_MAX+1. Of course, in order to do this, we need to widen them to 64bits ints. Task-number: QTBUG-48753 Change-Id: Ia4d808014dbf2a5575f4226779214bf0d5981f49 Reviewed-by: Lars Knoll --- src/qml/jsruntime/qv4mathobject.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src/qml/jsruntime') diff --git a/src/qml/jsruntime/qv4mathobject.cpp b/src/qml/jsruntime/qv4mathobject.cpp index f1face007c..3d3ac84576 100644 --- a/src/qml/jsruntime/qv4mathobject.cpp +++ b/src/qml/jsruntime/qv4mathobject.cpp @@ -277,10 +277,15 @@ Q_GLOBAL_STATIC(QThreadStorage, seedCreatedStorage); ReturnedValue MathObject::method_random(CallContext *context) { if (!seedCreatedStorage()->hasLocalData()) { - qsrand(QTime(0,0,0).msecsTo(QTime::currentTime()) ^ reinterpret_cast(context)); + int msecs = QTime(0,0,0).msecsTo(QTime::currentTime()); + Q_ASSERT(msecs >= 0); + qsrand(uint(uint(msecs) ^ reinterpret_cast(context))); seedCreatedStorage()->setLocalData(new bool(true)); } - return Encode(qrand() / (double) RAND_MAX); + // rand()/qrand() return a value where the upperbound is RAND_MAX inclusive. So, instead of + // dividing by RAND_MAX (which would return 0..RAND_MAX inclusive), we divide by RAND_MAX + 1. + qint64 upperLimit = qint64(RAND_MAX) + 1; + return Encode(qrand() / double(upperLimit)); } ReturnedValue MathObject::method_round(CallContext *context) -- cgit v1.2.3