I am trying to generate two random integers each with their own potential range of values. I keep a running sum of each value, and need to ensure that the ratio between these sums stays within range of a given value.
For each trial, I want both numbers to be random. Ie. I don't want to generate a single value and then calculate the other value to make the ratio I want.
The best solution I have found is for each trial, to just generate pairs of random numbers until The pair matches my constraints. However its not guaranteed to find a solution, and may loop for a long time.
import random
XMIN, XMAX = 64, 2500
YMIN, YMAX = 16, 2000
GOAL, THRESH =0.90, 0.03
def trial(sumX, sumY):
x,y=0,0
while True:
x = random.randint(XMIN,XMAX)
y = random.randint(YMIN,YMAX)
if abs( (sumX+x)/(sumX+x+sumY+y)-GOAL) <= THRESH:
return x,y
sumX,sumY=0,0
for I in range(10000):
x,y=trial(sumX,sumY)
trial_ratio = x/(x+y)
sumX, sumY = sumX+x, sumY+y
sum_ratio = sumX/(sumX+sumY)
print(f"+({x:5d}, {y:5d}) = {trial_ratio:0.2%} : ({sumX:8d}, {sumY:8d}) = {sum_ratio:0.2%}")
The snippet is in python, but the language doesn't matter
The above works as expected, however if possible I would like to be able to terminate faster than just making a random guess and throwing out invalid results.
Aucun commentaire:
Enregistrer un commentaire