Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar MSDN Visual Basic Community

Title Find the equation of a quadratic curve passing through three points This example shows how to find a quadratic equation through three points in Visual Basic 6. It plugs the coordinates of the points into the quadratic equation and solves for the equation's variables. It then draws the curve to show that it passes through the points. quadratic curve, quadratic equation, curve, points Graphics, Algorithms

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.

```Private Sub FindCurve()
Dim A As Double
Dim B As Double
Dim C As Double
Dim X As Double
Dim Y As Double

On Error GoTo NoCurve

' Calculate A, B, and C.
A = ((m_Y(2) - m_Y(1)) * (m_X(1) - m_X(3)) + _
(m_Y(3) - m_Y(1)) * (m_X(2) - m_X(1))) / _
((m_X(1) - m_X(3)) * (m_X(2) ^ 2 - m_X(1) ^ 2) + _
(m_X(2) - m_X(1)) * (m_X(3) ^ 2 - m_X(1) ^ 2))

B = ((m_Y(2) - m_Y(1)) - A * (m_X(2) ^ 2 - m_X(1) ^ 2)) _
/ (m_X(2) - m_X(1))

C = m_Y(1) - A * m_X(1) ^ 2 - B * m_X(1)

' Draw the curve.
CurrentX = 0
Y = C
If Y > 32000 Then Y = 32000
If Y < -32000 Then Y = -32000
CurrentY = Y
For X = 1 To ScaleWidth
Y = A * X ^ 2 + B * X + C
If Y > 32000 Then Y = 32000
If Y < -32000 Then Y = -32000
Line -(X, Y)
Next X

Me.Caption = _
Format\$(A, "0.0000") & ", " & _
Format\$(B, "0.0000") & ", " & _
Format\$(C, "0.0000")
Exit Sub

NoCurve:
MsgBox "No quadratic equation fits these points."
Exit Sub
End Sub```