python 脚本中的 barnsley fern 实现
barnsley fern implementation in python script
我正在编写一个脚本来在 Python 中重现巴恩斯利的蕨类植物,但是我得到了一些不同寻常的东西:
这是我的代码:
def iterate_vec(f, x0, a, steps=100):
"""x0: initial vector
a: parameter to f(x,a)"""
n = len(x0) # state dimension
x = np.zeros((steps+1, n))
x[0] = x0
for k in range(steps):
x[k+1] = f(x[k], a)
return(x)
def barnsley(x, A):
"""Barnley's fern:
x: initial point in 2D
a: matrices [A_0,...,A_m-1]"""
m = A.shape # should be (4, 2, 2), last column for bias
fs = [0,1,2,3]
i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07]) # choose one, in this case m[0] = 4, hence a randint btw 0 and 4
y = A[i] @ np.append(x[0],1) #in this case either first or second matrices are multiplied by vector x
return(y)
x = iterate_vec(barnsley, [0,0], A, 10000)
print(x.shape)
plt.plot(x[:,0], x[:,1], '.', markersize=0.5)
这是我的矩阵 A:
A = np.array([
[[0, 0],
[0, 0.16]],
[[0.85, 0.04],
[-0.04, 0.85]],
[[0.2, -0.26],
[0.23, 0.22]],
[[-0.15, 0.28],
[0.26, 0.24]],
])
这看起来是个有趣的问题。将您的代码与 Wikipedia 上的描述进行比较,您似乎缺少转换中的常量。我在下面添加了这些。
def barnsley(x, A):
"""Barnley's fern:
x: initial point in 2D
a: matrices [A_0,...,A_m-1]"""
m = A.shape # should be (4, 2, 2), last column for bias
fs = [0,1,2,3]
i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07])
y = A[i] @ np.append(x[0], x[1])
if i == 1 or i == 2:
y[1] += 1.6
elif i == 3:
y[1] += 0.44
return(y)
我正在编写一个脚本来在 Python 中重现巴恩斯利的蕨类植物,但是我得到了一些不同寻常的东西:
这是我的代码:
def iterate_vec(f, x0, a, steps=100):
"""x0: initial vector
a: parameter to f(x,a)"""
n = len(x0) # state dimension
x = np.zeros((steps+1, n))
x[0] = x0
for k in range(steps):
x[k+1] = f(x[k], a)
return(x)
def barnsley(x, A):
"""Barnley's fern:
x: initial point in 2D
a: matrices [A_0,...,A_m-1]"""
m = A.shape # should be (4, 2, 2), last column for bias
fs = [0,1,2,3]
i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07]) # choose one, in this case m[0] = 4, hence a randint btw 0 and 4
y = A[i] @ np.append(x[0],1) #in this case either first or second matrices are multiplied by vector x
return(y)
x = iterate_vec(barnsley, [0,0], A, 10000)
print(x.shape)
plt.plot(x[:,0], x[:,1], '.', markersize=0.5)
这是我的矩阵 A:
A = np.array([
[[0, 0],
[0, 0.16]],
[[0.85, 0.04],
[-0.04, 0.85]],
[[0.2, -0.26],
[0.23, 0.22]],
[[-0.15, 0.28],
[0.26, 0.24]],
])
这看起来是个有趣的问题。将您的代码与 Wikipedia 上的描述进行比较,您似乎缺少转换中的常量。我在下面添加了这些。
def barnsley(x, A):
"""Barnley's fern:
x: initial point in 2D
a: matrices [A_0,...,A_m-1]"""
m = A.shape # should be (4, 2, 2), last column for bias
fs = [0,1,2,3]
i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07])
y = A[i] @ np.append(x[0], x[1])
if i == 1 or i == 2:
y[1] += 1.6
elif i == 3:
y[1] += 0.44
return(y)