是否可以比平方距离算法更快地测试两个圆的交点?(Is it possible to test intersection of two circles faster than with squared

编程入门 行业动态 更新时间:2024-10-16 02:26:56
是否可以比平方距离算法更快地测试两个圆的交点?(Is it possible to test intersection of two circles faster than with squared-distance algorithm?)

我有这个代码来计算this圆是否与another圆相交。 我想要一个更快的版本,这可能吗?

this.CheckIntersection = function(another){ var xC = this.x; var yC = this.y; var GxC = another.x; var GyC = another.y; var distSq = (xC - GxC) * (xC - GxC) + (yC - GyC) * (yC - GyC); return distSq < (this.r + another.r) * (this.r + another.r); }

I have this code to calculate whether this circle intersections with another circle. I want a faster version, is that possible?

this.CheckIntersection = function(another){ var xC = this.x; var yC = this.y; var GxC = another.x; var GyC = another.y; var distSq = (xC - GxC) * (xC - GxC) + (yC - GyC) * (yC - GyC); return distSq < (this.r + another.r) * (this.r + another.r); }

最满意答案

那么你可以尝试改进这一点,如下所示:

this.CheckIntersection = function(another){ var dx = this.x-another.x; var dy = this.y-another.y; dx = dx*dx+dy*dy; dy = this.r+another.r; return dx < dy*dy; }

由于您节省了一些减法,因此速度会快一些,并且您使用的变量更少,因此运行时环境将更容易使用寄存器分配/缓存。

但就时间复杂性而言,你无能为力。 因此,您仅限于窥孔优化,例如寻找重复计算并尝试仅计算一次。

Well you can try to improve this a little bit as follows:

this.CheckIntersection = function(another){ var dx = this.x-another.x; var dy = this.y-another.y; dx = dx*dx+dy*dy; dy = this.r+another.r; return dx < dy*dy; }

This will be a bit faster since you save some subtractions, and you use less variables so the runtime environment will have an easier job with register allocation/caching.

But in terms of time complexity there is not much you can do. So you are limited to peephole optimization like for instance looking for duplicated computation and try to compute them only once.

更多推荐

本文发布于:2023-07-28 06:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1301660.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:交点   更快   算法   距离   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!