均匀B样条求基函数python代码
import numpy as np
def basis(x,degree,i,knots):
if degree==0:
if (x<knots[i+1])&(x>=knots[i]):
y=1
else:
y=0
else:
if (knots[degree+i]-knots[i])==0:
temp1=0
else:
temp1=(x-knots[i])/(knots[degree+i]-knots[i])
if knots[i+degree+1]-knots[i+1]==0:
temp2=0
else:
temp2=(knots[i+degree+1]-x)/(knots[i+degree+1]-knots[i+1])
y=temp1*basis(x, (degree-1), i, knots) +temp2*basis(x, (degree-1),(i+1), knots)
return y
def newbs(x,degree,inner_knots,Boundary_knots):
Boundary_knots=np.sort(Boundary_knots)
knots=[Boundary_knots[0]]*(degree+1)+list(np.sort(inner_knots))+[Boundary_knots[1]]*(degree+1)
n=len(inner_knots)+1+degree
s=[0]*n
if x==Boundary_knots[1]:
s[n]=1
else:
for i in range(n):
s[i]=basis(x,degree,i,knots)
return s
newbs(2, degree=3, inner_knots=[-0.25, -0.5, 0, 0.25, 0.5],Boundary_knots=[-4, 4])
根据Samiran Sinha的《A very short note on B-splines》部分中R语言的代码改编成python代码而来。有兴趣的小伙伴可以留言讨论呀~