Title: Graph a square curve in C#
This example shows how to graph a curve that draws a square. The basic idea isn't as bizarre as you might think. You probably know that x2 + y2 = 1 is the equation for a circle. So what is the equation for a square?
If you use the similar equation xN + yN = 1 where N is an increasingly large even integer, the equation approximates a square. For example, the picture at the top of this post shows the graph of the squarish curve x10 + y10 = 1.
By making N big enough, you can make the curve approximate a square to within any given tolerance. If you set N = 100, you can't really see a difference between the curve and a square.
You can't really plot the equation xN + yN = 1 directly, so the program solves it for y and actually graphs the following equation.
If the power N is an even integer, then this equation has two real solutions: a positive root and a negative root.
When you enter a positive, even, integer power in the text box and click Graph, the program makes a Bitmap and draws axes on it. That part is relatively straightforward so it isn't shown here. Download the example to see how it works.
The following code shows how the program draws the curve.
// Draw the curve.
private void DrawGraph(Graphics gr, Pen pen, float wxmin)
{
// Get the power.
int power = int.Parse(txtPower.Text);
float root = 1f / power;
// Even integer power. -1 <= x, y <= 1
List<PointF> points1 = new List<PointF>();
List<PointF> points2 = new List<PointF>();
for (float x = -1f; x <= 1f; x += 0.001f)
{
float y = -(float)Math.Pow(1 - Math.Pow(x, power), root);
points1.Add(new PointF(x, y));
points2.Add(new PointF(x, -y));
}
// Combine the lists.
points2.Reverse();
points1.AddRange(points2);
// Draw the curve.
gr.DrawPolygon(pen, points1.ToArray());
}
This code draws the graph of the equation shown above. It loops through values for x between -1 and 1 and uses the previous equation to find the corresponding y values.
The points that use positive y values move across the top of the square curve. The code saves them in the points1 array.
Similarly, the points that use negative y values move across the bottom of the square curve. The code saves them in the points2 array.
To easily draw the final curve, the program reverses the order of the points in the points2 array and adds those points to the end of the points1 array. The combined points now walk clockwise around the square curve.
The method finishes by drawing the points as a polygon.
Note that the code only works with even, positive, integer powers.
Download the example to experiment with it and to see additional details.
|