2;
if (n==0)
{
doSomthing()
}
doSomething() function will be executed at a probable (random) intervals based on this condition. However, any advice on how to make it more stable? Meaning to have a condition that will execute doSomthing() function exactly 50% or 30% of the whole run time.
U can use the rand function itself
n = rand() % 10; if (n > 4) {...} that will be for 50% theoretically, :)
n % 2 == 0, it will work even more precise :)
not necessarily
Thanks @hellozee, @gameraccoon Swastik
Everyone just uses modulus like that, but everyone ponders how to do better too... The usual attempt looks something like: #define N 100 // or whatever #define USE_MAX (N * (RAND_MAX/N)) // re-multiply and idiv truncate int x; do x = rand(); while(x >= USE_MAX); x %= N; I believe there is a better way but don't know off the top of my head.
If you're using C++ you'll better results using uniform https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution With values, for example 1,100 and probability to get value, for example < 20 will be 20% That makes it very easy to change probabilities when you need.
Обсуждают сегодня