使用渾沌遊戲演算法
30分鐘寫完,有chatgpt幫忙真的很快
這個演算法 稍微改一下就可以畫出不同的東西
#__________________________________________________________
coordinates <- data.frame(
x = c(0, 1, 0.5),
y = c(0, 0, sqrt(3)/2)
)
new_coordinates <- coordinates
#求中點函數
find_midpoint <- function(A, B) {
c(
x = (A["x"] + B["x"]) / 2,
y = (A["y"] + B["y"]) / 2
)
}
#隨機生成三角形內的點
random_point_in_triangle <- function(A, B, C) {
# 生成隨機數 u 和 v
u <- runif(1)
v <- runif(1)
# 調整 u 和 v 使得 u + v <= 1
if (u + v > 1) {
u <- 1 - u
v <- 1 - v
}
# 計算隨機點的座標
x <- (1 - u - v) * A["x"] + u * B["x"] + v * C["x"]
y <- (1 - u - v) * A["y"] + u * B["y"] + v * C["y"]
return(c(x = x, y = y))
}
#環境設定完畢__________________________________________________________
point_a <- random_point_in_triangle(unlist(coordinates[1, ]),unlist(coordinates[2,]),unlist(coordinates[3,]))
names(point_a) <- c("x", "y")
loop <- 10000
for (i in 1:loop){
#隨機選一個頂點
pickd_point <-unlist(coordinates[sample(1:3, size = 1, replace = TRUE), ])
names(pickd_point) <- c("x","y")
#把A點映射到中點
new_point <- find_midpoint(point_a,pickd_point)
names(new_point) <- c("x", "y")
#儲存新點
new_row <- data.frame(
x = new_point["x"],
y = new_point["y"]
)
new_coordinates <- rbind(new_coordinates,new_row)
#把點迭代回去
point_a <- new_point
cat(i,"點",point_a,"\n")
}
plot(new_coordinates)