#1,148 – Sample Code to Convert from Polar to Cartesian Coordinates
September 1, 2014 3 Comments
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));
if ((angleDeg = 360.0)) should be if ((angleDeg = 360.0))
Strange, my comment got mangled. Line 8: radius must be angleDeg
Thanks for the catch, Ferenc!