可扩展的有偏数生成器 - Python [英] Extensible biased number generator - Python

查看:47
本文介绍了可扩展的有偏数生成器 - 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

这很有效,但它有时会给出完全离谱的数字;例如它曾经为 (1,100,30,60) 给出了 -246174068358.我想那里只有一个我没有看到的错误.

This works pretty well, however it has on occasion given completely outrageous numbers; e.g. it once gave -246174068358 for (1,100,30,60). I figure there is just a bug in there that I am not seeing.

提前致谢.

推荐答案

raise 退出函数——你不需要跟着 raise 跟 return

raise exits the function - you do not need to follow raise with return

range(lo, hi) 中的目标效率低下;为什么不 lo <= target <嗨?

target in range(lo, hi) is inefficient; why not lo <= target < hi?

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

随着步数的增加,这将很快收敛到目标;您可能需要进行一些试验分布以确保获得预期的结果,或者尝试改用 random.gauss.

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.

这篇关于可扩展的有偏数生成器 - Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆