-2

I need to determine a,b,c value of y=ax2+bx+c using the set of data point which varies upto 100 points.For Ex (-270,69) (-269,90) (-280,50). I have used Using points to generate quadratic equation to interpolate data url for determine the a,b,c value.but I found the difference between a,b,c value in both method. Note: I can not use Numpy into production code.

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
>>>
4

1 回答 1

4

您是否在 SO 上发布之前拆分了计算行b和行?c粘贴在问题中的代码将无法编译。这个版本可以:

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

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

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

于 2013-10-04T07:24:59.760 回答