HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Converting from polar coordinates to rectangular coordinates

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
coordinatespolarrectangularconvertingfrom

Problem

This is performance critical. I measured and determined that using the sqrt is faster then using the cos method.

I am aware that this code only works for some points, so that is not an issue.

Point is System.Drawing.Point. _offset is also of type Point.

I assumed, and the profiler seemed to confirm, that the try/catch will not slow down the code unless an exception occurs. Please correct me if that is wrong.

/// 
/// Convert from polar coordinates to rectangular coordinates.
/// Only works for points to the left of the origin.
/// 
/// The radius of the point in pixels.
/// The angle of the point in radians.
/// The point in rectangular coordinates.
internal Point PolarToRectangular(
        double radius,
        double theta)
{
    try
    {
        double sin = Math.Sin(theta);

        // This is faster then:
        // double cos = Math.Cos(theta);
        double cos = -Math.Sqrt(1 - (sin * sin));

        Int32 x = _offset.X + (Int32)Math.Round(radius * cos);
        Int32 y = _offset.Y + (Int32)Math.Round(radius * sin);

        return new Point(x, y);
    }
    catch (OverflowException ex)
    {
        ex.Data.Add("Screen polar Radius", radius);
        ex.Data.Add("Screen polar Theta", theta);
        throw;
    }
}

Solution

I would consider using a lookup table to find your sines. How precise an angle are you calculating for? This answer on stackoverflow has some interesting information on how to construct one and the benchmarks for using it to two decimal points. If you are using the full precision of a double, then your current method will be faster, but if you have a fixed precision, a lookup table will be benificial.

As long as the exception IS exceptional (and it looks to me like it is) it will add very little overhead to your run times. See: https://stackoverflow.com/q/52312/487663.

Context

StackExchange Code Review Q#183, answer score: 17

Revisions (0)

No revisions yet.