我正在嘗試使用 Chaos 游戲在 Python 中生成一個 Spierpinki 三角形。然而,要繪制的點的計算似乎是正確的,而不是繪制了數千個點,而只繪制了 10 個左右的點。
import math
import numpy as np
import random as rand
import matplotlib.pyplot as plt
# Defining vertices
t = np.linspace(0, (2 * math.pi), 4)
v = np.array([[math.cos(t[0]), math.cos(t[1]), math.cos(t[2])],
[math.sin(t[0]), math.sin(t[1]), math.sin(t[2])]])
# Defining Starting point
T = np.array([[0.5, 0], [0, 0.5]])
x = np.array([rand.random() - 0.5, rand.random() - 0.5]).reshape(2, 1)
res = np.zeros((2, 1))
n = 10000
for i in range(n):
for j in range(2):
k = rand.randint(0, 2)
res = np.expand_dims(res, axis=0)
res = np.multiply(T, np.subtract(x[j], v[:, k])) v[:, k]
xx = [x for (x, y) in res]
yy = [y for (x, y) in res]
plt.plot(xx, yy, 'b.')
plt.show()

uj5u.com熱心網友回復:
首先,歡迎來到SO。你的問題很好解釋。您的代碼是獨立的。多好的第一個問題。
要繪制的點的計算似乎是正確的。
不完全的。您的代碼存在多個問題。有些是實際的錯誤,盡管很容易犯。例如,rand.randint(0,2)給你一個區間 [0, 2) 上的隨機整數。請注意,您永遠無法通過這種方式獲得 2,并且永遠不會選擇您的第三個頂點。
更大的問題是代碼的復雜性。一個內部回圈j不會改變任何東西。矩陣乘法以彼此減去 2 個點。等等。它變得如此復雜,以至于您永遠不會注意到x/res永遠不會更新,以至于您一遍又一遍地繪制相同的點。你應該努力更簡單地表達想法。優雅的數學符號可以作為代碼的起點,但很少是終點。
這是我的代碼的簡化版本。
import numpy as np
import matplotlib.pyplot as plt
# Defining vertices
t = np.linspace(0, (2 * np.pi), 4)
v = np.array([[np.cos(t[0]), np.cos(t[1]), np.cos(t[2])],
[np.sin(t[0]), np.sin(t[1]), np.sin(t[2])]])
# Defining Starting point
x = np.array([0., 0.])
# Loop
for k in np.random.randint(3, size=1000):
x = 0.5 * (v[:, k] - x)
plt.plot(x[0], x[1], 'b.')
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/363521.html
標籤:Python 麻木的 matplotlib 数学 混乱
下一篇:如何在lambdify中使用字典
