更快的数学运算
可能的重复:
极地快速算法 ->笛卡尔转换
我正在通过 jvisualvm 运行一些寻路代码(有点慢),我发现 80% 的时间花在我的向量实现上,更具体地说是将笛卡尔转换为极坐标的部分,
r = Math.sqrt((x * x) + (y * y));
t = Math.atan2(y,x);
有没有什么老派技巧可以让我获得更多表现吗?
Possible Duplicate:
Fast algorithm for polar -> cartesian conversion
I am running some pathfinding code (which is a bit slow) through jvisualvm, what I found was that 80% time is being spent in my vector implementation more specifically the part that convert cartesian to polar,
r = Math.sqrt((x * x) + (y * y));
t = Math.atan2(y,x);
are there any old school tricks that would get me some more performance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据我在路径查找算法方面的经验,问题不在于那些线。
主要问题是“您调用这两行多少次?”
您应该研究您的路径查找算法。
无论如何,如果您想减少这些线路的延迟,可以为每个
x
的sqrt
和atan2
制作一个预先计算的表和y
。或者甚至是一个将每个 (x, y) 直接映射到 (r, t) 的表。In my experience in path finding algorithms, the problem is not those lines.
The main questions is "How many times you call these two lines?"
You should investigate your path finding algorithm.
Anyway, if you want reduce the delay of those lines, it is possible to make a pre-calculated table for
sqrt
andatan2
for eachx
andy
. Or even a table that maps each (x, y) to (r, t) directly.您应该考虑是否确实需要使用
Math.atan2()
。根据我的经验,很少有几何计算真正需要实际角度;通过使用更自然的操作,您可以获得更快、更简单、更可靠的结果。例如,如果您想计算两个向量(例如
a
和b
)之间的角度,您可以经常使用点积:和一种 rump "叉积”:
这种“叉积”特别有用,因为该符号告诉您向量
b
指向向量a
的哪一侧。如果事实证明您确实需要一个角度(通常用于人类可读的输出),那么这些值是为
atan2()
的输入量身定制的。You should consider if you really need to use
Math.atan2()
. In my experience there are very few geometric computations that really need the actual angle; you can get faster, simpler, and more robust results by using more natural operations.For example, if you want to evaluate the angle between two vectors (say,
a
andb
), you can instead often use the dot product:and a kind of rump "cross product":
This "cross product" is especially useful because the sign tells you which side of vector
a
the vectorb
points to.If it turns out you really do need an angle (usually for human-readable output), these values are tailor made for input to
atan2()
.