A quadratic equation has the form:
Y = A * X^2 + B * X + C
Since we have three points, we have three sets of values for X and Y. That gives us three equations and three unknowns: A, B, and C.
Plugging in the points (X1, Y1), (X2, Y2), and (X3, Y3) gives:
Y1 = AX1^2 + BX1 + C
Y2 = AX2^2 + BX2 + C
Y3 = AX3^2 + BX3 + C
Subtracting equation 1 from the other two gives:
Y2 - Y1 = A(X2^2 - X1^2) + B(X2-X1)
Y3 - Y1 = A(X3^2 - X1^2) + B(X3-X1)
Multiplying the first equation by (X1-X3) and the second by (X2-X1) and adding them gives:
(Y2-Y1)(X1-X3) = (X1-X3)A(X2^2 - X1^2) + B(X2-X1)(X1-X3)
(Y3-Y1)(X2-X1) = (X2-X1)A(X3^2 - X1^2) + B(X3-X1)(X2-X1)
Or
(Y2-Y1)(X1-X3) + (Y3-Y1)(X2-X1) = A[(X1-X3)(X2^2-X1^2) + (X2-X1)(X3^2-X1^2)]
Solving for A gives:
A = [(Y2-Y1)(X1-X3) + (Y3-Y1)(X2-X1)]/[(X1-X3)(X2^2-X1^2) + (X2-X1)(X3^2-X1^2)]
Plugging into the previous equation gives:
B = [(Y2 - Y1) - A(X2^2 - X1^2)] / (X2-X1)
Plugging into the original equation gives:
C = Y1 - AX1^2 - BX1
This all looks horrible, but we have the values for Y1, Y2, Y3, X1, X2, and X3 so we just plug them in. The example does that to find A, B, and C. It then graphs the function so you can see it passes through the points.
Note that Visual Basic has trouble drawing lines with cordinates greater than 32,767 so the program does a little checking to ensure that the Y values are always between -32,000 and 32,000.
My book Visual Basic Graphics Programming shows lots of other ways to fit curves to a set of points.
|