[SERVER-70107] Buildfest feedback: should $rand exclude 1? Created: 29/Sep/22  Updated: 27/Oct/23  Resolved: 25/Nov/22

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: 6.0.1
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Maxim Katcharov Assignee: Alexander Ignatyev
Resolution: Works as Designed Votes: 0
Labels: buildfest-2022
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Problem/Incident
Operating System: ALL
Sprint: QO 2022-10-17, QO 2022-10-31, QO 2022-11-14, QO 2022-11-28
Participants:

 Description   

Should $rand be exclusive of 1? Languages with this type of rand (Java, Python, C#...) exclude 1. This simplifies getElement(int(rand()*length)), since there is no chance (however minor) of going out of bounds, which a user may be caught off guard by.

Otherwise, is there a reason that $rand should include 1?



 Comments   
Comment by Alexander Ignatyev [ 25/Nov/22 ]

Created a DOCS ticket to clarify the docs: https://jira.mongodb.org/browse/DOCSP-26331

Comment by Maxim Katcharov [ 14/Nov/22 ]

Thank you for confirming. I thought this based on the wording in https://www.mongodb.com/docs/manual/reference/operator/query/rand/ "$rand returns a random float between 0 and 1". I will open a docs issue, asking specify "between 0 (inclusive) and 1 (exclusive)". This issue can be closed.

Comment by Alexander Ignatyev [ 03/Nov/22 ]

Hi Maxim, why do you think $rand includes 1, as far as I can see from its implementation it does not:

 

// src/mongo/db/pipeline/expression.h
static constexpr double kMinValue = 0.0;
static constexpr double kMaxValue = 1.0;    
// src/mongo/db/pipeline/expression.cpp
double ExpressionRandom::getRandomValue() const {
    return kMinValue + (kMaxValue - kMinValue) * threadLocalRNG.nextCanonicalDouble();
}
    
// src/mongo/platform/random.h
/** A random number in the range [0, 1). */
double nextCanonicalDouble() {
    return std::uniform_real_distribution<double>{0, 1}(_urbg);
}

Generated at Thu Feb 08 06:15:17 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.