I am trying to get a random number generator that will be biased in that it takes a number, and prints a number that is likely to be close. Here's what I have now:
def biasedRandom(rangen, rangex, target, biaslevel=1):
if rangen > rangex:
raise ValueError("Min value is less than max value.")
return
if not target in range(rangen, rangex):
raise ValueError("Bias target not inside range of random.")
return
num = random.randint(rangen, rangex)
for i in range(biaslevel):
distance = abs(num - target)
num -= random.randint(0, distance)
return num
This works pretty well, however it has on occasion given completely outrageous numbers; eg it once gave -246174068358
for (1,100,30,60)
. I figure there is just a bug in there that I am not seeing.
Thanks in advance.
raise exits the function - you do not need to follow raise with return
target in range(lo, hi) is inefficient; why not lo <= target < hi?
Edit:
import random
def biasedRandom(lo, hi, target, steps=1):
if lo >= hi:
raise ValueError("lo should be less than hi")
elif target < lo or target >= hi:
raise ValueError("target not in range(lo, hi)")
else:
num = random.randint(lo, hi)
for i in range(steps):
num += int(random.random() * (target - num))
return num
As steps is increased, this will pretty rapidly converge on target; you might want to do some trial distributions to make sure that you are getting what you expected, or try using random.gauss instead.
在计算num的最后一行,你是否在想这样的事情?
num = abs(num - random.randint(0,distance))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.