0
我正在嘗試使用參數方程隨機生成線段的程序。我所創造的種類完成了這項工作,但不是線路彼此斷開連接,而是形成一條線路。這是我用python寫的。使用參數方程的隨機線段
enter import numpy as np
import random as rand
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
npoints = 10
V = np.zeros(npoints)
def point1 (npoints):
x0 = np.zeros(npoints)
y0 = np.zeros(npoints)
z0 = np.zeros(npoints)
for k in range (npoints):
theta = rand.uniform(0.0, np.pi)
phi = rand.uniform(0.0, (2 * np.pi))
x0[k] = 10 * np.sin(phi) * np.cos(theta)
y0[k] = 10 * np.sin(phi) * np.sin(theta)
z0[k] = 10 * np.cos(theta)
return np.array([x0,y0,z0])
def point2 (npoints):
x1 = np.zeros(npoints)
y1 = np.zeros(npoints)
z1 = np.zeros(npoints)
for j in range (npoints):
theta = rand.uniform(0.0, np.pi)
phi = rand.uniform(0.0, (2 * np.pi))
x1[j] = 10 * np.sin(phi) * np.cos(theta)
y1[j] = 10 * np.sin(phi) * np.sin(theta)
z1[j] = 10 * np.cos(theta)
return np.array([x1,y1,z1])
n = 10
def t_parameter(n):
t = np.zeros(n)
for i in range (n):
t[i] = rand.uniform(-10,10)
return np.array([t])
p1 = point1(npoints)
p2 = point2(npoints)
V = p2-p1
d = t_paramiter(n)
Lx = d*V[0]+p1[0]
Ly = d*V[1]+p1[1]
Lz = d*V[2]+p1[2]
ax.plot_wireframe(Lx,Ly,Lz)
當我運行代碼時,這就是生成的內容plot of what is generated。我想編碼做的是保持初始點和方向矢量的值不變,而只需用隨機值更新d。
我試圖做這樣的事情
Lx = np.zeros(npoints)
Ly = np.zeros(npoints)
Lz = np.zeros(npoints)
for i in range (n):
Lx[i] = d[i]*V[i]+p1[i]
Ly[i] = d[i]*V[i]+p1[i]
Lz[i] = d[i]*V[i]+p1[i]
,但我得到一個錯誤「設置與序列的數組元素」。
隱式修正縮進和拼寫錯誤:由於您返回了'np.array([t])','t_parameter()'函數會返回一個2D數組(儘管1維)。因此,'d'是二維的,'d [i]'是一個數組而不是標量。只需從't_parameter()'返回't',你就可以走了。 – Evert
請注意,NumPy有一個[矢量化的統一隨機程序](https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.random.uniform.html#numpy.random.uniform)。你可以簡單地執行'd = np.random.uniform(-10,10,n)'並刪除整個't_parameter()'函數。 – Evert