我非常感谢 Mark Dickinson's suggestion 使用三角函数生成两个平方和为 1 的随机数。这是最重要的三角恒等式之一,有时被称为 正弦和余弦的毕达哥拉斯公式强>
sine^2 (theta) + cos^2(theta) = 1
因此,我们在区间[-pi, pi] 中随机抽样theta 并取其中的sine 和cosine。这给了我们两个数字,当它们独立平方然后相加时将等于 1。
所以,实现看起来像:
def squared_unity():
r = np.random.uniform(-np.pi, np.pi)
r1, r2 = np.cos(r), np.sin(r)
# sanity check
sq_sum = np.sum(np.square([r1, r2]))
print("the two random numbers are: {}, {}".format(round(r1, 4), round(r2, 4)))
print("sum of the squares of them is: {}".format(round(sq_sum, 4)))
In [172]: for i in range(10):
...: squared_unity()
the two random numbers are: -0.4232, 0.906
sum of the squares of them is: 1.0
the two random numbers are: -0.6432, 0.7657
sum of the squares of them is: 1.0
the two random numbers are: -0.9854, 0.1701
sum of the squares of them is: 1.0
the two random numbers are: 0.6192, -0.7852
sum of the squares of them is: 1.0
the two random numbers are: 0.613, 0.7901
sum of the squares of them is: 1.0
the two random numbers are: 0.3289, -0.9444
sum of the squares of them is: 1.0
the two random numbers are: -0.6289, -0.7775
sum of the squares of them is: 1.0
the two random numbers are: 0.5851, 0.811
sum of the squares of them is: 1.0
the two random numbers are: -0.9515, 0.3076
sum of the squares of them is: 1.0
the two random numbers are: 0.992, -0.1258
sum of the squares of them is: 1.0