1

I have an animal that lives in a while loop for many days.

At the end of the day, there is a 40% chance she gives birth,

class Animal
{
public:
  double chance_of_birth;
  ...

  public Animal(..., int chance)
  {
    this.chance_of_birth = chance;
    ...
  }
}

// create this animal
Animal this_animal = new Animal(..., .50);

Given that every animal I create can have a specific chance of giving birth, how can I write a condition that evaluates true only chance_of_birth percent of the time?

I know I want to use rand(), but I never used it like this before.

Along the lines of

if(this_animal->chance_of_birth ???)
{
  //will give birth
}
manlio
  • 18,345
  • 14
  • 76
  • 126
user3487243
  • 183
  • 1
  • 11
  • [random_number](http://stackoverflow.com/questions/686353/c-random-float-number-generation) < change_of_birth – martijnn2008 Apr 16 '16 at 18:13
  • If you want to use rand(), which returns an int you will have to do somthing like: `double rn = rand() % 10000; rn /= 10000.0; if (chance > rn) {/*code*/}` – DarthRubik Apr 16 '16 at 18:16
  • @DarthRubik This helped me a lot thank you! – user3487243 Apr 16 '16 at 18:26
  • This is gonna be biased a little, since rand returns (purportedly) uniformly distributed value out of 2³¹ possibilities. – bipll Apr 16 '16 at 21:38

1 Answers1

2

Since c++11 you can use the library <random>.
In the example below I'm using std::uniform_real_distribution<> to generate a random floating point value within the range 0 - 1

#include <iostream>
#include <random>
using namespace std;

double random(int min, int max)
{ // we make the generator and distribution 'static' to keep their state
  // across calls to the function.
    std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_real_distribution<> dis(min, max);
    return dis(gen);
}

int main()
{
    double f = random(0,1); // range 0 - 1
    cout << f << '\n';
}

Now you can use that random floating point value in an if statement to run only when a condition is true.

if (f <= 0.40) { ... }
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
  • There's a small oversight: the `std::mt19937` PRNG should be `static` (or `thread_local`), not the `random` function. Currently `random` doesn't return the same value every time because the PRNG is initialized with a different seed at every call. Nevertheless it's suboptimal since it's slow and the smooth functioning of `gen` isn't ensured. – manlio Apr 16 '16 at 21:17
  • If `gen` isn't `static` every call of `random` implies: 1. a call of `rd()` (the performance of many implementations of `random_device` degrades sharply once the entropy pool is exhausted) 2. the construction of a new (not so small) `mt19937` object. Moreover usually you seed the PRNG just once (e.g. http://stackoverflow.com/a/7320944/3235496) – manlio Apr 16 '16 at 21:58