#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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Ferenc Németh says:

    if ((angleDeg = 360.0)) should be if ((angleDeg = 360.0))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: