简体   繁体   English

可扩展的偏置数字生成器 - Python

[英]Extensible biased number generator - Python

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) . 例如,曾经给过-246174068358 (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 raise退出函数 - 你不需要跟随加注返回

target in range(lo, hi) is inefficient; 范围内的目标(lo,hi)是低效的; why not lo <= target < hi? 为什么不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. 您可能希望进行一些试验分发,以确保获得预期,或尝试使用random.gauss。

在计算num的最后一行,你是否在想这样的事情?

    num = abs(num - random.randint(0,distance))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM