Translating Equations to Algorithms

116 Views Asked by At

I can't understand equations. But I'm a software engineer. I think the brevity of the equation is confusing to me where a program spells it all out.

Trying to translate the equation for a bezier curve into javascript. The equation on wikipedia appears as-

enter image description here

Translating this to javascript looks like this-

function B(t, p0, p1, p2, p3) {
  return Math.pow((1 - t), 3) * p0 + 3 * Math.pow((1 - t), 2) * p1 + 3 * (1 - t) * Math.pow(t, 2) * p2 + Math.pow(t, 3) * p3;
}

But this doesn't make sense. A point is made up of an x and y coordinate. How can multiple values be represented by a single value in a meaningful way? How is this equation usable?

1

There are 1 best solutions below

1
On BEST ANSWER

As others have mentioned, the "$\mathbf{P}$" things are 2D points; each of them has an $x$ coordinate and a $y$ coordinate. Or, actually, in some situations, the $\mathbf{P}$ objects might be 3D points having $x$ , $y$ and $z$ coordinates.

So, suppose $\mathbf{P}_0$ has coordinates $(x_0,y_0)$, and, similarly, $\mathbf{P}_1 = (x_1,y_1)$, $\mathbf{P}_2 = (x_2,y_2)$, and $\mathbf{P}_3 = (x_3,y_3)$. Then the necessary code is:

s = 1-t
f0 = s*s*s
f1 = 3*s*s*t
f2 = 3*s*t*t
f3 = t*t*t

x = f0*x0 + f1*x1 + f2*x2 + f3*x3
y = f0*y0 + f1*y1 + f2*y2 + f3*y3

There are ways to write this that involve slightly fewer arithmetic operations, but I thought clarity would be more important than performance, at this stage.

I don't know much about Javascript, but in other languages (C# for example) you would create a Point class and you would overload the "+" and "*" operators. Then you woud be able to write code that looks exactly like the formula you cited:

p = f0*p0 + f1*p1 + f2*p2 + f3*p3

Here f0*p0 represents the number f0 multiplied by the point p0, and so on.