

利用Mathematica 8的CompilationTarget將程式利用gcc編譯,速度果然快很多。由上面的範例可發現,有無編譯在計算謝爾賓斯基三角形當n=10時速度差了21倍。
newpt[x_List] := {{x[[1]], Mean@{x[[1]], x[[2]]},
Mean@{x[[1]], x[[3]]}}, {x[[2]], Mean@{x[[2]], x[[1]]},
Mean@{x[[2]], x[[3]]}}, {x[[3]], Mean@{x[[3]], x[[1]]},
Mean@{x[[3]], x[[2]]}}};
Stgraphtest1[pt_List,n_Integer] := Nest[Flatten[Map[newpt, #], 1] &, {pt}, n];
Stgraphtest2 = Compile[{{x, _Real, 2}, {n, _Integer}},
Nest[Flatten[Map[newpt, #], 1] &, {x}, n], {{newpt[__], _Real, 3}},
CompilationTarget -> "C"]
Stgraph =
Compile[ {{pt, _Real, 2}, {n, _Integer}},
Nest[Flatten[
Map[{{#[[1]], Mean@{#[[1]], #[[2]]},
Mean@{#[[1]], #[[3]]}}, {#[[2]], Mean@{#[[2]], #[[1]]},
Mean@{#[[2]], #[[3]]}}, {#[[3]], Mean@{#[[3]], #[[1]]},
Mean@{#[[3]], #[[2]]}}} &, #], 1] &,
{pt}, n],
CompilationTarget -> "C"
];
pt = {{0, 0}, {2, 0}, {1, Sqrt[3]}};
First@AbsoluteTiming@Stgraph[pt, 8]
First@AbsoluteTiming@Stgraphtest1[pt, 8]
First@AbsoluteTiming@Stgraphtest2[pt, 8]
Graphics[{Red, Polygon /@ Stgraph[pt, 8]}]
Manipulate[Block[{p1 = point1, p2 = point2, p3 = point3},
Graphics[{Red, Polygon /@ Stgraph[{p1, p2, p3}, i]},
PlotRange -> {{-1, 3}, {-1, 3}}]],
{{point1, {0, 0}}, Locator},
{{point2, {2, 0}}, Locator},
{{point3, {1, Sqrt[3]}}, Locator},
{i, 1, 10, 1}]

讀者回應 ( 0 意見 )
訂閱發佈留言 (Atom)
發佈留言
Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.
如果這篇文章對你有幫助,那請留個訊息給我~