# Implemented Cubic Spline is not smooth

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:

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:

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?

## 1 Answer

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.

• 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. – AlexP Sep 8 '13 at 20:56