I want to implement cubic spline, so I found and implemented this discription and this method for solving tridiagonal system. I'd like to draw without using any math libraries, so cubic spline is displayed by taking each piece of the spline, $Y_i(t)$, and connecting the points $(x_i + t*(x_{i+1} - x_i), Y_i(t))$ for $t$ between 0 and 1.

Now, when all $x_i$ are ascending and far enough from each other, spline looks good, like this: enter image description here

But when more complicated cubic spline takes place (like in the description) by placing adjacent point vertically or in opposite direction, produced spline is not smooth:

enter image description here enter image description here

What am I missing? Is there another type of spline, that doesn't have sharp corners (and picture in description was misplaced)? Or am I doing something wrong?


The picture on the Wolfram web page is highly misleading. It could not be produced by the algorithm they describe (without some significant modifications -- see below). The spline they describe (which you implemented) gives $y$ as a function of $x$. The algorithm relies on the fact that the input $x$ values are strictly increasing. So, in your second and third examples, I'm surprised that your code didn't crash.

The other common type of spline curve is a parametric spline. This has an equation of the form $\mathbf C(t) = \left( x(t), y(t) \right)$, where $x$ and $y$ are now spline functions that depend on a parameter $t$. With this approach, you can have curves that are vertical, or double back in the $x$-direction (like the one shown in the picture on the Wolfram site).

You can construct parametric cubic splines using the code you already wrote. Suppose you have data points $P_i = (x_i,y_i)$. First, you assign a parameter value $t_i$ to each data point $P_i$. There are many ways to do this, but the main point is that the $t_i$ values must be strictly increasing. Then use your code to compute a spline function $x(t)$ that fits the data $(t_i,x_i)$ and another spline function $y(t)$ that fits the data $(t_i,y_i)$. Then the curve $\mathbf C(t) = \left( x(t), y(t) \right)$ is what you want.

  • $\begingroup$ Got it working. What I did is found function for x axis the same way as for y, but independently from latter. Resulted (x(t), y(t)) is exactly what I was looking for. $\endgroup$ – AlexP Sep 8 '13 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.