sqrt
比使用cos
方法要快。我知道这段代码仅适用于某些点,所以这不是问题。
Point
是System.Drawing.Point
。 _offset
的类型也为Point
。我认为,探查器似乎确认,除非出现异常,否则
try
/ catch
不会降低代码速度。如果那是错误的,请纠正我。/// <summary>
/// Convert from polar coordinates to rectangular coordinates.
/// Only works for points to the left of the origin.
/// </summary>
/// <param name="radius">The radius of the point in pixels.</param>
/// <param name="theta">The angle of the point in radians.</param>
/// <returns>The point in rectangular coordinates.</returns>
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;
}
}
#1 楼
是的,我认为这很快。可能很想移动cos calc,以使其对半径进行完整的毕达哥拉斯。这将保存一个分配,但是我需要额外的乘法(在您的当前版本中已经知道1 * 1)。作为个人风格的问题(可能是因为我使用多种语言编写代码)但我会为您的sin和cos变量使用不同的名称。大多数语言都不会接受这一点,因此,就个人而言,它有可能使我感到困惑。
#2 楼
我会考虑使用查找表查找您的病情。您计算的角度有多精确?关于stackoverflow的答案提供了一些有趣的信息,如如何构造一个以及将其使用两个小数点的基准。如果您使用双精度的全精度,则当前方法会更快,但是如果您具有固定精度,则查询表将是有益的。对我来说,它的运行时间几乎不会增加。请参阅:https://stackoverflow.com/q/52312/487663。#3 楼
作为完全未经测试的微优化,我怀疑(Int32)(radius * cosTheta + 0.5)
的速度会比(Int32)Math.Round(radius * cosTheta)
快一点。但是,它的确舍入为0.5而不是舍入,这可能不是您想要的。