#1,148 – Sample Code to Convert from Polar to Cartesian Coordinates

Below is some simple code (not productized) that can convert from two-dimensional polar to cartesian coordinates.

    public class PolarPoint
    {
        // Angle expressed in degrees
        public PolarPoint(double radius, double angleDeg)
        {
            if (radius < 0.0)
                throw new ArgumentException("Radius must be non-negative");
            if ((angleDeg < 0) || (angleDeg >= 360.0))
                throw new ArgumentException("Angle must be in range [0,360)");

            Radius = radius;
            AngleDeg = angleDeg;
        }

        // Polar coordinates
        public double Radius { get; set; }
        public double AngleDeg { get; set; }

        // Cartesian coordinates
        public double X
        {
            get { return Radius * Math.Cos(AngleDeg * Math.PI / 180.0); }
        }

        public double Y
        {
            get { return Radius * Math.Sin(AngleDeg * Math.PI / 180.0); }
        }

        public override string ToString()
        {
            return string.Format("({0},{1})", X, Y);
        }
    }

We can then use this class as follows.

            Console.WriteLine(new PolarPoint(0.0, 0.0));
            Console.WriteLine(new PolarPoint(1.0, 0.0));
            Console.WriteLine(new PolarPoint(1.0, 45.0));
            Console.WriteLine(new PolarPoint(1.0, 90.0));
            Console.WriteLine(new PolarPoint(1.0, 135.0));
            Console.WriteLine(new PolarPoint(1.0, 180.0));

1148-001

Advertisement

#1,146 – Polar Coordinate System

In most cases when you’re working with graphical objects, you use a cartesian coordinate system, where each point is represented as an X and a Y value, indicating the point’s distance from an origin in two different dimensions.

You can also express points in a two-dimensional system using a polar coordinate system.  Each point in a polar coordinate system is represented with two values:

  • A radius value, describing how far the point is from an origin  (range is any non-negative number)
  • An angular coordinate, describing how many degrees around the circle the point is located, typically from a horizontal ray extending to the right of the origin  (range typically [0, 360) degrees or [0, 2*pi) radians)

Below is a picture showing two sample points expressed in polar coordinates.

  • (2.0, 60) – Radius = 2, Angle = 60 degrees (counterclockwise) from horizontal
  • (1.0, 180) – Radius = 1, Angle = 180 degrees (counterclockwise) from horizontal

1146-001