How to generate a boolean with p probability using C rand() function?
Solution 1
bool nextBool(double probability)
{
return (rand() / (double)RAND_MAX) < probability;
}
or (after seeing other responses)
bool nextBool(double probability)
{
return rand() < probability * ((double)RAND_MAX + 1.0);
}
Solution 2
Do you mean generate a random variable so that p(1) = p and p(0) = (1-p)?
If so, compare the output of rand()
to p*RAND_MAX
.
Jake Petroules
Software developer primarily self taught since age 12. Experience in design and development of computer programs, websites, and database systems, 3D graphics, UI design and usability, cross-platform development, and open source software. Co-founded a software company (Petroules Corporation) in college which developed data security software (Silverlock). Active developer in the Open Source Qt Project (qt.io) from late 2012 to early 2018. Key contributor to the Qbs (pronounced "Cubes") build system since its early history. Worked at The Qt Company from late 2015 to early 2018. Working at Apple in the Developer Tools team (Xcode, llbuild, etc.) since February 2018. Studied computer science at Keene State College and took courses at the Massachusetts Institute of Technology and online courses through Stanford University. Specialties: C, C++, Objective-C, Swift, macOS, iOS, Xcode, build automation, cross-platform, qbs, Qt, security & cryptography, UX and UI design
Updated on July 25, 2022Comments
-
Jake Petroules over 1 year
How can I generate a random boolean with a probability of
p
(where 0 <= p <= 1.0) using the C standard libraryrand()
function?i.e.
bool nextBool(double probability) { return ... }
-
Colin over 13 yearsThe second one might actually be faster. They're mathematically identical.
-
caf over 13 yearsThat needs to be
probability * (RAND_MAX + 1)
- otherwise, passing a value of1.0
asprobability
will result in the function returning 0 sometimes. -
leemes over 11 yearsThank you very much. I fixed a minor issue in your second version, as the
+1
generated an integer overflow