Python 3.x 函数在给定圆中生成多个随机点
我定义了一个函数,在给定的圆中生成一个随机数:Python 3.x 函数在给定圆中生成多个随机点,python-3.x,random,Python 3.x,Random,我定义了一个函数,在给定的圆中生成一个随机数: def rand_gen(R,c): # random angle alpha = 2 * math.pi * random.random() # random radius r = R * math.sqrt(random.random()) # calculating coordinates x = r * math.cos(alpha) + c[0] y = r * math.sin(a
def rand_gen(R,c):
# random angle
alpha = 2 * math.pi * random.random()
# random radius
r = R * math.sqrt(random.random())
# calculating coordinates
x = r * math.cos(alpha) + c[0]
y = r * math.sin(alpha) + c[1]
return (x,y)
现在我想添加一个参数n(
rand_gen(R,c,n)
),这样我们就可以得到n个这样的数字,而不是一个
import math
import random
def rand_gen(R, c, n):
out = []
for i in range(n):
# random angle
alpha = 2 * math.pi * random.random()
# random radius
r = R * math.sqrt(random.random())
# calculating coordinates
x = r * math.cos(alpha) + c[0]
y = r * math.sin(alpha) + c[1]
out.append((x,y))
return out
print(rand_gen(10, (3, 4), 3))
打印(例如):
但我认为更好的方法是保持函数不变,并使用列表理解生成n个点:
lst = [rand_gen(10, (3, 4)) for _ in range(3)]
print(lst)
印刷品:
[(-1.891474340814674, -2.922205399732765), (12.557063558442614, 1.9323688240857821), (-5.450160078420653, 7.974550456763403)]
如果要生成
n
随机点,可以使用参数和for循环扩展函数:
import math
import random
def rand_gen(R, c, n):
out = []
for i in range(n):
# random angle
alpha = 2 * math.pi * random.random()
# random radius
r = R * math.sqrt(random.random())
# calculating coordinates
x = r * math.cos(alpha) + c[0]
y = r * math.sin(alpha) + c[1]
out.append((x,y))
return out
print(rand_gen(10, (3, 4), 3))
打印(例如):
但我认为更好的方法是保持函数不变,并使用列表理解生成n个点:
lst = [rand_gen(10, (3, 4)) for _ in range(3)]
print(lst)
印刷品:
[(-1.891474340814674, -2.922205399732765), (12.557063558442614, 1.9323688240857821), (-5.450160078420653, 7.974550456763403)]
您还可以使用生成器功能实现该目标:
随机导入
输入数学
def随机发电机(右、中、北):
而n:
#随机角
alpha=2*math.pi*random.random()
#随机半径
r=r*math.sqrt(random.random())
#计算坐标
x=r*math.cos(alpha)+c[0]
y=r*math.sin(alpha)+c[1]
n-=1
产量(x,y)
点数=随机数(10,(3,4),4)
对于points in points_gen:
打印(点)
分数=[*兰特(10,(3,4),4)]
打印(点数)
您也可以使用生成器功能实现该目标:
随机导入
输入数学
def随机发电机(右、中、北):
而n:
#随机角
alpha=2*math.pi*random.random()
#随机半径
r=r*math.sqrt(random.random())
#计算坐标
x=r*math.cos(alpha)+c[0]
y=r*math.sin(alpha)+c[1]
n-=1
产量(x,y)
点数=随机数(10,(3,4),4)
对于points in points_gen:
打印(点)
分数=[*兰特(10,(3,4),4)]
打印(点数)
如果我想将输出列表转换为形状(n,2)的numpy数组,我该怎么做so@Xtense你可以做arr=np.array([rand_gen(10,(3,4))for u in range(3)])
将列表转换为numpy数组。如果我想将输出列表转换为形状(n,2)的numpy数组,我该怎么办so@Xtense您可以执行arr=np.array([rand\u gen(10,(3,4))用于范围内(3)])
将列表转换为numpy数组。