2017-08-02 42 views
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] 

,但我得到一個錯誤「設置與序列的數組元素」。

+1

隱式修正縮進和拼寫錯誤:由於您返回了'np.array([t])','t_parameter()'函數會返回一個2D數組(儘管1維)。因此,'d'是二維的,'d [i]'是一個數組而不是標量。只需從't_parameter()'返回't',你就可以走了。 – Evert

+1

請注意,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

回答

0

我沒有足夠的代表處發表評論,但一對夫婦的快速說明:

  • 是你的正常工作在你的代碼縮進?他們不顯示在這裏縮進(至少對我來說)。這適用於point1point2t_parameter
  • 行中存在拼寫錯誤d:d = t_paramiter(n)應該是d = t_parameter(n)

請注意,您只繪製了一系列的隨機的線的端點: d*V[0]+p1[0]是終點的x值,也不行。我的知識在此結束,但您需要分別繪製10個獨立系列的兩個點,而您目前正在繪製一個包含10個點的系列。

希望有幫助!