[Python] Drawing a B-spline

Discussão em 'Python' iniciado por Stack, Junho 7, 2025.

  1. Stack

    Stack Membro Participativo

    From the Wikipedia article:


    In the mathematical subfield of numerical analysis, de Boor's algorithm is a polynomial-time and numerically stable algorithm for evaluating spline curves in B-spline form. It is a generalization of de Casteljau's algorithm for Bézier curves. The algorithm was devised by German-American mathematician Carl R. de Boor. Simplified, potentially faster variants of the de Boor algorithm have been created but they suffer from comparatively lower stability.
    ​

    That article offers what it calls a "naive" implementation

    def deBoor(k: int, x: int, t, c, p: int):
    """Evaluates S(x).

    Arguments
    ---------
    k: Index of knot interval that contains x.
    x: Position.
    t: Array of knot positions, needs to be padded as described above.
    c: Array of control points.
    p: Degree of B-spline.
    """
    d = [c[j + k - p] for j in range(0, p + 1)]

    for r in range(1, p + 1):
    for j in range(p, r - 1, -1):
    alpha = (x - t[j + k - p]) / (t[j + 1 + k - r] - t[j + k - p])
    d[j] = (1.0 - alpha) * d[j - 1] + alpha * d[j]

    return d[p]


    I have this problem: It looks like the c array goes out of bounds in the first line of code

    d = [c[j + k - p] for j in range(0, p + 1)]


    When generating the first point the first loop through range(0, p + 1) for a 3rd degree spline

    j = 0;
    k = 0;
    p = 3;


    so d[0] will be set to c[ -3 ]

    Question: How do I prevent attempts to access negative indices of c?

    Note 1: I tried checking for negative indices and accessing c[0] instead. The results look OK, but can this be correct?

    Side question, in this line

    alpha = (x - t[j + k - p]) / (t[j + 1 + k - r] - t[j + k - p])


    should there not be a check to prevent divide by zero?

    Continue reading...

Compartilhe esta Página