gpt4 book ai didi

algorithm - 在 Mathematica 中迭代生成 Sierpinski 三角形?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:27:24 25 4
gpt4 key购买 nike

我编写了绘制 Sierpinski 分形的代码。它真的很慢,因为它使用递归。你们中有人知道我如何在不递归的情况下编写相同的代码以使其更快吗?这是我的代码:

 midpoint[p1_, p2_] := Mean[{p1, p2}]
trianglesurface[A_, B_, C_] := Graphics[Polygon[{A, B, C}]]
sierpinski[A_, B_, C_, 0] := trianglesurface[A, B, C]
sierpinski[A_, B_, C_, n_Integer] :=
Show[
sierpinski[A, midpoint[A, B], midpoint[C, A], n - 1],
sierpinski[B, midpoint[A, B], midpoint[B, C], n - 1],
sierpinski[C, midpoint[C, A], midpoint[C, B], n - 1]
]

编辑:

我已经用混沌游戏方法编写了它,以防有人感兴趣。感谢您的精彩回答!这是代码:

 random[A_, B_, C_] := Module[{a, result},
a = RandomInteger[2];
Which[a == 0, result = A,
a == 1, result = B,
a == 2, result = C]]

Chaos[A_List, B_List, C_List, S_List, n_Integer] :=
Module[{list},
list = NestList[Mean[{random[A, B, C], #}] &,
Mean[{random[A, B, C], S}], n];
ListPlot[list, Axes -> False, PlotStyle -> PointSize[0.001]]]

最佳答案

这使用 ScaleTranslate 结合 Nest 来创建三角形列表。

Manipulate[
Graphics[{Nest[
Translate[Scale[#, 1/2, {0, 0}], pts/2] &, {Polygon[pts]}, depth]},
PlotRange -> {{0, 1}, {0, 1}}, PlotRangePadding -> .2],
{{pts, {{0, 0}, {1, 0}, {1/2, 1}}}, Locator},
{{depth, 4}, Range[7]}]

Mathematica graphics

关于algorithm - 在 Mathematica 中迭代生成 Sierpinski 三角形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9068987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com