# "Bezier_curves.py"# @Fumihachiimport matplotlib.pyplot as plt
import numpy as np
from numpy.random import *
from scipy.special import comb
defbernstein(n, i, t):
return comb(n, i) * t ** i * (1 - t) ** (n - i)
defbezier_curve(n, t, p):
return np.dot([bernstein(n, i, t) for i inrange(n + 1)], p)
# 制御点をランダムに生成
N = 4# Number of control points
L = 10# Max range of X, Y
p = rand(N, 2) * L # Create control points
p = p[p[:, 0].argsort(), :] # Sort to x-axisprint(p)
# Calculate
x = np.array([bezier_curve(N - 1, t, p) for t in np.linspace(0, 1, 100)])
# Draw
plt.plot(p[:, 0], p[:, 1], marker='o')
plt.plot(x[:, 0], x[:, 1])
plt.title('Bezier curve')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid('on')
plt.show()
Julia
# "Bezier_curves.jl"# @Fumihachiusing PyPlot
using LinearAlgebra
function bernstein(n, i, t)
return binomial(n, i) * t^i * (1-t)^(n-i)
endfunction bezier_curve(n, t, p)
x = [dot([bernstein(n, i, t) for i = 0:n], p[:,1]) dot([bernstein(n, i, t) for i = 0:n], p[:,2])];
return x
end# Create control points at random
N = 4;
L = 10;
p = rand(N, 2) * L;
p = p[sortperm(p[:,1]), :]
# Calculate
nt = 100
x = Array{Float64,2}(undef, nt+1, 2)
for k = 1:nt+1
x[k,:] = bezier_curve(N - 1, (k-1)/100, p)
end# Draw
plot(p[:,1], p[:,2], marker="o")
plot(x[:,1], x[:,2])
title("Bezier curve")
xlabel("X")
ylabel("Y")
grid("on")
show()