在numpy中是否有一些简单的工具,给定一个值x返回三个随机坐标,其模数为x?
答案 0 :(得分:2)
好吧,我不认为你会为了这个目的找到一些numpy的东西,但这会非常快:
from numpy.random import normal
from numpy.linalg import norm
from numpy import allclose
def random_vec(modulus):
while True:
y = normal(size=(3,))
if not allclose(y,0):
y *= modulus / norm(y)
return y
上面我假设使用向量的模块你的意思是L2范数。请注意,我们必须检查至少一个坐标是否不太接近零(或零!),这样我们在重新缩放组件时就没有数字舍入问题。
编辑:现在使用normal()
代替rand()
我们解释了为什么我们从正态分布中选取坐标(然后当然是重新缩放它们)以便在半径modulus
的球体上获得随机点的原因here。另请阅读下面的unutbu评论。
答案 1 :(得分:0)
假设你想要三维笛卡尔坐标(X,Y,Z)
,你可以在球面极坐标中选择两个角度,然后转换回笛卡尔坐标:
import numpy as np
# Example data: three values of x = sqrt(X^2 + Y^2 + Z^2)
x = np.array([1, 2, 2.5])
n = len(x)
theta = np.arccos(2 * np.random.random(n) - 1)
phi = np.random.random(n) * 2. * np.pi
X = x * np.sin(theta) * np.cos(phi)
Y = x * np.sin(theta) * np.sin(phi)
Z = x * np.cos(theta)
给出(例如):
[-2.60520852 0.01145881 1.01482376]
[-0.85300437 0.29508229 -1.54315779]
[ 1.21871742 -0.95540313 3.54806944]