使用数据点确定二次方程的a,b,c

时间:2013-10-04 06:50:30

标签: python python-2.7

我需要使用数据点集来确定y=ax2+bx+c的a,b,c值,该数据点的变化高达100点。对于Ex(-270,69)( - 269,90)(-280,50) )。我使用Using points to generate quadratic equation to interpolate data url来确定a,b,c值。但我发现两种方法中a,b,c值之间的差异。 注意:我不能将Numpy用于生产代码。

def coefficent(x,y):
    x_1 = x[0]
    x_2 = x[1]
    x_3 = x[2]
    y_1 = y[0]
    y_2 = y[1]
    y_3 = y[2]

    a = y_1/((x_1-x_2)*(x_1-x_3)) + y_2/((x_2-x_1)*(x_2-x_3)) + y_3/((x_3-x_1)*(x_3-x_2))

    b = -y_1*(x_2+x_3)/((x_1-x_2)*(x_1-x_3))
    -y_2*(x_1+x_3)/((x_2-x_1)*(x_2-x_3))
    -y_3*(x_1+x_2)/((x_3-x_1)*(x_3-x_2))

    c = y_1*x_2*x_3/((x_1-x_2)*(x_1-x_3))
    + y_2*x_1*x_3/((x_2-x_1)*(x_2-x_3))
    + y_3*x_1*x_2/((x_3-x_1)*(x_3-x_2))

    return a,b,c

x = [1,2,3]
y = [4,7,12]

a,b,c = coefficent(x, y)
print a,b,c


> import numpy as np
>>> A, B, C = np.polyfit([1,2,3],[4,7,12],2)
>>> print A, B, C
1.0 -4.2727620148e-15 3.0
>>> print A, 'x^2 +', B, 'x +', C
1.0 x^2 + -4.2727620148e-15 x + 3.0
>>>

1 个答案:

答案 0 :(得分:1)

在发布SO之前,您是否拆分了计算bc的行?粘贴在问题中的代码将无法编译。这个版本确实:

def coefficient(x,y):
    x_1 = x[0]
    x_2 = x[1]
    x_3 = x[2]
    y_1 = y[0]
    y_2 = y[1]
    y_3 = y[2]

    a = y_1/((x_1-x_2)*(x_1-x_3)) + y_2/((x_2-x_1)*(x_2-x_3)) + y_3/((x_3-x_1)*(x_3-x_2))

    b = (-y_1*(x_2+x_3)/((x_1-x_2)*(x_1-x_3))
         -y_2*(x_1+x_3)/((x_2-x_1)*(x_2-x_3))
         -y_3*(x_1+x_2)/((x_3-x_1)*(x_3-x_2)))

    c = (y_1*x_2*x_3/((x_1-x_2)*(x_1-x_3))
        +y_2*x_1*x_3/((x_2-x_1)*(x_2-x_3))
        +y_3*x_1*x_2/((x_3-x_1)*(x_3-x_2)))

    return a,b,c

x = [1,2,3]
y = [4,7,12]

a,b,c = coefficient(x, y)

print "a = ", a
print "b = ", b
print "c = ", c

输出无可挑剔:

a =  1
b =  0
c =  3

这比b的答案更准确(numpy系数的4 * 10 -15 左右)。对于三个数据点,它在数学上也是准确的。

您的代码给您的答案有什么问题?