Title: Select a conic section in C#
This example shows how you can let the user click five points to select a conic section. Recall that the equation for a conic section is:
If you know the coordinates of some points on a conic section, then you can plug their X and Y coordinates into this general equation to get a system of equations with the unknown values A, B, C, D, E, and F.
You can also arbitrarily set one of those values. For example, you can set F = 1. (Suppose you find an equation for the same conic section where F = f ≠ 1. Then simply divide A, B, C, D, E, and F by f to get another equation for the same conic section where F = 1.)
To let the user select a conic section, this example lets you click to select five points. It then plugs the points' X and Y coordinates into the general equation with F = 1 to get five equations and five unknowns A, B, C, D, and E. It then uses Gaussian elimination to solve the equations for A, B, C, D, and E.
For information on how to use Gaussian elimination, see the post Use Gaussian elimination to solve a system of equations in C#.
Due to the coordinates used by the example's PictureBox, this example tends to produce very small values for most of the constants A, B, C, D, and E. The tiny values cause some problems when determining which kind of conic section the equation represents. To make working with the values easier, this example scales the results so the smallest coefficient (in absolute value) is 1. (The same logic that says you can arbitrarily set F = 1 lets you set the smallest coefficient to 1.)
After the program uses Gaussian elimination to find A, B, C, D, and E, it uses the techniques described in the example Draw a conic section from its polynomial equation in C# to draw the selected conic section.
See the code for additional details.
This method still doesn't handle some odd cases. For example, if you select five points that have the same X coordinate, then Gaussian elimination doesn't produce a unique solution. (The conic section would be the degenerate case of a line.)
Another unusual case occurs if the conic section's equation should have F = 0. If F = 0, then the step that assumes F = 1 is invalid. You would still have five equations and five unknowns but this program doesn't solve the equations correctly in that case.
This program doesn't look for these odd cases. It simply crashes. (You can add code to look for them if you like.)
Download the example to experiment with it and to see additional details.
|