Tenshou
- 153
- 1
I am not sure how to assign probabilities to variables do you think you guys will be able to help me?
The discussion revolves around assigning probabilities to variables in C++ programming, particularly in the context of using conditional statements and loops. Participants explore how to implement probabilistic behavior in code, including generating random numbers and structuring loops.
Participants generally agree on the approach of using random numbers to simulate probabilities in C++, but there are varying suggestions on how to implement loops and manage conditions. The discussion remains unresolved regarding the best practices for maintaining loops and assigning probabilities.
Some participants mention the limitations of the rand() function as a pseudo-random number generator, but do not reach a consensus on its adequacy for the task at hand. There is also a lack of clarity on the specifics of loop termination conditions.
#include <stdlib.h> // C standard library
float num = rand() % 9; // this is the C rand function, and your number will be between 0-8
if (num < 3)
{
// do something
}
else if (num >= 3 && num <= 6)
{
// do something else
}
else // implication num > 6 && num <= 8
{
// do something else
}
Adyssa said:I don't use C++, but you can generate a random number and then decide on a course of action depending on the result. For example:
Code:#include <stdlib.h> // C standard library float num = rand() % 9; // this is the C rand function, and your number will be between 0-8 if (num < 3) { // do something } else if (num >= 3 && num <= 6) { // do something else } else // implication num > 6 && num <= 8 { // do something else }
Your random number will be in one of the 3 ranges with 1/3 probability, although it's worth noting that rand() is a pseudo-random number generator, but it's probably fine for your purposes.
What Adyssa wrote is NOT a loop; it's an if...else block. To make this a loop, you would need to embed the if-else block in a loop of some kind.Tenshou said:Thank you! How would you make this loop keep going without terminating?
Tenshou said:so I would make a bool variable and have it always true while the conditional is looping or something of that fashion?
while (true) {
// do something
}
while (1)
{
Get a random number (in the range 0 .. RAND_MAX)
Turn it into a probability by dividing by RAND_MAX
if (prob < .3333)
{
do something
}
else if (prob < .6666)
{
do something else
}
else
{
do the third thing
}
}