我需要构建一个多项式函数,例如 a_0 + a_1 x + a_2 x^2 ...我正在尝试执行整个插值过程。我有这个:def Create_F(Numero, Array): Y = lambda x: x Lista = list(Array) F_x = [] for i in range(Numero): G_x = lambda x: eval(Lista[i]*Y^i) F_x.append(G_x) return F_x如果我使用这个,我不会得到任何帮助:Number = 2ma = np.array([[1, 1], [1, 2]])ly = np.array([8, -3])idk = Create_F(Number, ly)print(idk)我不知道如何评估,例如1。如果我能以更好的方式做到这一点,那将非常有帮助,完整的代码是:import numpy as npdef Matrix_F(Num, Lx): Vec = np.zeros((Num, Num), dtype = float) Vec.T[1] = Lx ex = 0 for i in range(Num): for j in range(Num): Vec[j][i]=Lx[j]**ex ex += 1 return Vecdef Cramer_F(Ma, Ly): Lc, Det = np.array(Ly), np.linalg.det(Ma) col = len(Lc) Values = np.zeros(col) for i in range(col): org = Ma.copy() org.T[i]=Lc Di=np.linalg.det(org) Values[i] = Di/Det error = np.linalg.norm(np.dot(Ma, Values)-Lc) return Values, error def Create_F(Numero, Array): Y = lambda x: x Lista = list(Array) F_x = [] for i in range(Numero): G_x = lambda x: eval(Lista[i]*Y^i) F_x.append(G_x) return F_xval = int(input('Ingrese la cantidad de valores de X y Y que posee: '))x_val = []y_val = []print('Ingrese %s valores de cada variable:' %(val))n = 1for i in range(val): x = float(input('%s° Valor de x: '%(n))) y = float(input('%s° Valor de y: '%(n))) x_val.append(x) y_val.append(y) n += 1#Matriz del sistema:As = Matrix_F(val, x_val)#Valores de "a_n" y errora_val, er = Cramer_F(As, y_val)n=0print()for i in a_val: print('a_%s = %.6f' %(n, i)) n += 1感谢您抽出时间!
1 回答
慕妹3242003
TA贡献1824条经验 获得超6个赞
如果我想到了,您可能想创建一个多项式表示形式作为 lambda 函数。所以让我建议替代函数:
import numpy as np
def alternative_create_F(coeffs):
Y = lambda x: sum([item*(x**iter) for iter, item in enumerate(coeffs)])
return Y
coeffs = np.array([8, -3, 4]) # first is the free coeff second is x coeff and so on
idk = alternative_create_F(coeffs)
print(idk(3))
print(idk(6))
请注意该number变量是不相关的,因为您可以从len(coeffs).
现在 lambda 函数保存多项式的表示 -
coeffs[0] + coeffs[1]*x + coeffs[2]*x^2
要调用 lambda 函数,请将其作为具有所需 x 值的函数来调用。从我的示例收到的输出:
35 ===> 8+(-3)*3+4*3^2 = 8-9+36 = 35
134 ===> 8+(-3)*6+4*6^2 = 8-18+144 = 134
希望你觉得它有用
添加回答
举报
0/150
提交
取消