I appear to be awful at describing the question so I'll try and describe the problem.
I want to add a random amount of heads to my creatures but I want to be able to determine several things. a) The minimum number of possible heads b) The maximum number of possible heads c) The probability of the number being high/low within the above values.
So i could add heads like so: addHeads(5, 10, 0.5); // should produce creatures with "around" 7.5 heads but they could have anywhere from 5 to 10.
So random number generation isn't the problem, but controlling and actually using them in a game is. :D
Answer
One way to do it is to apply a power function. Start with a random number in [0, 1] and then raise it to the power of some positive number. Powers < 1 will bias upward, i.e. the numbers will be more likely to be higher than lower within [0, 1], and powers > 1 will bias downward. Then use multiplication and addition to shift the range of numbers from [0, 1] to your desired range. In pseudocode:
function random(low, high, bias)
{
float r = rand01(); // random between 0 and 1
r = pow(r, bias);
return low + (high - low) * r;
}
// Examples:
random(5, 10, 1.0); // between 5 and 10, average is 7.5
random(5, 10, 0.5); // between 5 and 10, average is somewhere around 8.5
random(5, 10, 2.0); // between 5 and 10, average is somewhere around 6.5
Here's a plot of the second example:
On the horizontal is the initial random number in [0, 1] and on the vertical is the output. You can see that something like 75% of the initial range is mapped to values higher than 7.5, and 25% of the initial range is mapped below 7.5. So the result is that numbers generated by this function are more likely to be higher.
No comments:
Post a Comment