python生成规定随机数_如何在python中生成超出范围的随机数?

我能想到的最简单的蛮力方法是生成一个所有有效点的列表并使用random.choice()从此列表中进行选择。这将为列表使用几MB内存,但是生成点非常快:import random

screen_width = 1000

screen_height = 800

rect_x = 500

rect_y = 250

rect_width = 100

rect_height = 75

valid_points = []

for x in range(screen_width):

if rect_x <= x < (rect_x + rect_width):

for y in range(rect_y):

valid_points.append( (x, y) )

for y in range(rect_y + rect_height, screen_height):

valid_points.append( (x, y) )

else:

for y in range(screen_height):

valid_points.append( (x, y) )

for i in range(10):

rand_point = random.choice(valid_points)

print(rand_point)

可以生成一个随机数并将其映射到屏幕上的有效点,这会减少内存,但它有点混乱,需要更多的时间来生成这个点。可能有一种更清晰的方法可以做到这一点,但是使用与上面相同的屏幕大小变量的一种方法是:rand_max = (screen_width * screen_height) - (rect_width * rect_height)

def rand_point():

rand_raw = random.randint(0, rand_max-1)

x = rand_raw % screen_width

y = rand_raw // screen_width

if rect_y <= y < rect_y+rect_height and rect_x <= x < rect_x+rect_width:

rand_raw = rand_max + (y-rect_y) * rect_width + (x-rect_x)

x = rand_raw % screen_width

y = rand_raw // screen_width

return (x, y)

这里的逻辑类似于从旧的8位和16位微处理器上的x和y坐标计算屏幕地址的反方法。变量等于有效屏幕坐标的数目。计算像素的x和y坐标,如果x和y位于矩形内,则将像素推到上方。,进入第一次调用无法生成的区域。

如果您不太关心一致随机点,这个解决方案很容易实现,而且非常快速。x值是随机的,但如果所选的X位于带有矩形的列中,则Y值受到约束,因此矩形上方和下面的像素比矩形的左右两个位置的比萨更容易被选择:def pseudo_rand_point():

x = random.randint(0, screen_width-1)

if rect_x <= x < rect_x + rect_width:

y = random.randint(0, screen_height-rect_height-1)

if y >= rect_y:

y += rect_height

else:

y = random.randint(0, screen_height-1)

return (x, y)

另一个答案是计算像素在屏幕某些区域的概率,但他们的答案还不完全正确。下面是一个使用类似想法的版本,计算像素在给定区域中的概率,然后计算出像素在该区域内的位置:valid_screen_pixels = screen_width*screen_height - rect_width * rect_height

prob_left = float(rect_x * screen_height) / valid_screen_pixels

prob_right = float((screen_width - rect_x - rect_width) * screen_height) / valid_screen_pixels

prob_above_rect = float(rect_y) / (screen_height-rect_height)

def generate_rand():

ymin, ymax = 0, screen_height-1

xrand = random.random()

if xrand < prob_left:

xmin, xmax = 0, rect_x-1

elif xrand > (1-prob_right):

xmin, xmax = rect_x+rect_width, screen_width-1

else:

xmin, xmax = rect_x, rect_x+rect_width-1

yrand = random.random()

if yrand < prob_above_rect:

ymax = rect_y-1

else:

ymin=rect_y+rect_height

x = random.randrange(xmin, xmax)

y = random.randrange(ymin, ymax)

return (x, y)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值