How to generate a boolean with p probability using C rand() function?

10,541

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.

Share:
10,541
Jake Petroules
Author by

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 &amp; cryptography, UX and UI design

Updated on July 25, 2022

Comments

  • Jake Petroules
    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 library rand() function?

    i.e.

    bool nextBool(double probability)
    {
        return ...
    }
    
  • Colin
    Colin over 13 years
    The second one might actually be faster. They're mathematically identical.
  • caf
    caf over 13 years
    That needs to be probability * (RAND_MAX + 1) - otherwise, passing a value of 1.0 as probability will result in the function returning 0 sometimes.
  • leemes
    leemes over 11 years
    Thank you very much. I fixed a minor issue in your second version, as the +1 generated an integer overflow