Hydrotronics
Hydrotronics

Reputation: 5

Random number that prefers a range

I'm trying to write a program that requires me to generator a random number.

I also need to make it so there's a variable chance to pick a set range.

In this case, I would be generating between 1-10 and the range with the percent chance is 7-10.

How would I do this? Could I be supplied with a formula or something like that?

Upvotes: 0

Views: 65

Answers (1)

Ben Hershey
Ben Hershey

Reputation: 370

So if I'm understanding your question, you want two number ranges, and a variable-defined probability that the one range will be selected. This can be described mathematically as a probability density function (PDF), which in this case would also take your "chance" variable as an argument. If, for example, your 7-10 range is more likely than the rest of the 1-10 range, your PDF might look something like:

Sample Probability Density Function

One PDF such as a flat distribution can be transformed into another via a transformation function, which would allow you to generate a uniformly random number and transform it to your own density function. See here for the rigorous mathematics: http://www.stat.cmu.edu/~shyun/probclass16/transformations.pdf

But since you're writing a program and not a mathematics thesis, I suggest that the easiest way is to just generate two random numbers. The first decides which range to use, and the second generates the number within your chosen range. Keep in mind that if your ranges overlap (1-10 and 7-10 obviously do) then the overlapping region will be even more likely, so you will probably want to make your ranges exclusive so you can more easily control the probabilities. You haven't said what language you're using, but here's a simple example in Python:

import random

range_chance = 30 #30 percent change of the 7-10 range

if random.uniform(0,100) < range_chance:
  print(random.uniform(7,10))
else:
  print(random.uniform(1,7)) #1-7 so that there is no overlapping region

Upvotes: 1

Related Questions