如何在 python 中创建函数,使它们 return x 作为变量? (插值)

How to create functions in python such that they return x as a variable? (interpolation)

如何在 Python 中创建函数,例如:

n = int(input("number of knots: "))

xsolmed=[]

for i in range(n+1):
    xsolmed.append(-1+(2*i/n))

def x(x):
    return x
lni=[]
formula=1

for i in range(n+1):
    for j in range(n+1):
        if i==j:
            pass
        formula = (x(x)-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula

我想我需要它来 return 函数,这样公式变量本身就是 x 的函数,所以稍后我可以以时尚的方式调用它

formula(10)=output

formula(10) 是一个函数的实例,因此只有一个值而不是要分配给的变量名。

编写上述代码的一个好方法是:

n = int(input("number of knots: "))

xsolmed=[]

for i in range(n+1):
    xsolmed.append(-1+(2*i/n))

def y(x):
    return x

def formula_calc(X):
    formula=1

    for i in range(n+1):
        for j in range(n+1):
            if i==j:
                pass
            formula = (X-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula

    return formula

# now formula is a function of x. X can itself be a function.
print(formula(y(7))
# this will print value of formula at 7 as x(7) is 7.

将函数调用的结果设置为您想要的变量。

def f(x):
    "A function that changes nothing"
    return x

a = f(5) # same as a = 5

为避免混淆,我建议您不要为函数指定与其参数相同的名称(即不要这样做 def x(x): ...)。

如果您希望 formula 成为一个函数,则将其声明为一个函数,之后正确的语法将是 output = formula(10).