I use Mathematica to implement the de Casteljau algorithm
$$\vec{P}_{k,i}(u_0)=(1-u_0)\vec{P}_{k-1,i}(u_0)+u_0\vec{P}_{k-1,i+1}(u_0)$$
The graphics that de Casteljau algorithm generated as follows:
My trial
(*The recursion formula*)
P[k_, i_, u0_] :=
(1 - u0) P[k - 1, i, u0] + u0 P[k - 1, i + 1, u0]
(*Initial values*)
P[0, 0, 2/5] = {0, 0};
P[0, 1, 2/5] = {2, 4};
P[0, 2, 2/5] = {4, 5};
P[0, 3, 2/5] = {6, 0};
ptsData = Table[P[k, i, 2/5], {k, 0, 3}, {i, 0, 3 - k}];
pts = {{0, 0}, {2, 4}, {4, 5}, {6, 0}};
Graphics[
Join[Point /@ ptsData, Line /@ ptsData, {Red, BezierCurve[pts]}]]
It works well.
So I packed these codes to a function deCasteljau[]
deCasteljau[pts_, u_] :=
Module[{p, ptsdata, n},
n = Length@pts - 1;
Table[p[0, j, u], {j, 0, n}] = pts;
p[k_, i_, u0_] :=(1 - u0) p[k - 1, i, u0] + u0 p[k - 1, i + 1, u0];
ptsdata = Table[p[k, i, u], {k, 0, n}, {i, 0, n - k}];
Graphics[
Join[Point /@ ptsdata, Line /@ ptsdata, {Red, BezierCurve[pts]}]]
]
However, it failed.
deCasteljau[{{0, 0}, {2, 4}, {4, 5}, {6, 0}}, 2/5]
I felt that the main question is the recursion formula p[k_, i_, u0_] :=(1 - u0) p[k - 1, i, u0] + u0 p[k - 1, i + 1, u0];
But I cannot deal with it by myself smoothly.
Question:
How to revise it?(Or how to avoid using the recursion formula. Namely, using Mathematica construction to replace it)
Edit
Thanks for kale help
When I input
?j
Global`j
In general, the variable j
in construction Table[p[0, j, u], {j, 0, n}]
should be local.