Question

I'm trying to implement the recursive definition for B-Splines in c# but I can't get it right. Here's what I've done:

public static Double RecursiveBSpline(int i, Double[] t, int order, Double x)
{
    Double result = 0;

    if (order == 0)
    {
        if (t[i] <= x && x < t[i + 1])
        {
            result = 1;
        }
        else
        {
            result = 0;
        }
    }
    else
    {
        Double denom1, denom2, num1, num2;

        denom1 = t[i + order + 1] - t[i + 1];
        denom2 = t[i + order] - t[i];

        if (denom1 == 0)
        {
            num1 = 0;
        }
        else
        {
            num1 = t[i + order + 1] - x / denom1;
        }

        if (denom2 == 0)
        {
            num2 = 0;
        }
        else
        {
            num2 = x - t[i] / denom2;
        }

        result = num1 * RecursiveBSpline(i + 1, t, order - 1, x) 
            + num2 * RecursiveBSpline(i, t, order - 1, x);
    }

    return result;
}

And here is how I call the function:

Double[] vect = new Double[] { 0, 1, 2, 3 };

MessageBox.Show(BSpline.RecursiveBSpline(0,vect,2,0.5).ToString());

I should see 0,125 on the screen, instead I get 0,25. The two denominator variables are used to check if they equal 0 and if they do, the number should be set to 0 by definition. Can someone point out where I'm getting this wrong?

Was it helpful?

Solution

Bear in mind, that the mathematical and logical operators in C# have a precedence order. Your second solution works fine if you put the right terms in braces (explanation follows). This line:

num2 = x - t[i] / denom2;

should be changed to:

num2 = (x - t[i]) / denom2;

and so on. Then the result is as desired: 0.125

The division operator has a higher order precedence as the addition operator. To affect the execution order use braces (everything in braces will be evaluated at first):

var r1 = 2 + 2 / 2; // Step1: 2 / 2 = 1 Step2: 2 + 1 Output: 3
var r2 = (2 + 2) / 2;   // Step1: (2 + 2) = 4 Step2: 4 / 2 = 2 Output: 2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top