计算两个CGPoint之间距离的最快方法? [英] Fastest way to calculate the distance between two CGPoints?

查看:93
本文介绍了计算两个CGPoint之间距离的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两点之间的距离:

sqrt((x1-x2)^2 + (y1-y2)^2)

有没有一种方法可以在Objective-C中更快地完成此数学运算?

Is there a way to do this math faster in objective-C ?

我想我需要在上面澄清一下.我写了上面的公式只是为了澄清我用来计算距离的公式. ^并不表示xor-我只是想表示数学公式,而不使用pow等任何函数,所以我的意思是使用^来加电".我想知道是否有人知道使用按位运算符,或者以其他方式在汇编中编写代码是否会提供优化的版本.我正在iPhone/iPad应用程序中使用该公式.

I think I need to clarify above. I wrote the formula above just to clarify what formula I am using to calculate the distance. ^ is not meant to represent xor - I just wanted to represent the mathematical formula without using any functions like pow or anything, so I meant to use ^ to "raise to the power off". I was wondering if anyone knows if using bitwise operators, or otherwise writing code in assembly would give an optimized version. I am using the formula in an iPhone / iPad application.

推荐答案

否,如果您需要确切的距离,则无法击败该公式.

No, if you need the exact distance you cannot beat that formula.

尽管要清楚,^不是用于平方值的运算符,而是执行xor的位运算符.

Although to be clear ^ is not an operator for squaring a value, but a bit operator that does xor.

您将需要类似的东西

double dx = (x2-x1);
double dy = (y2-y1);
double dist = sqrt(dx*dx + dy*dy);

如果您只可以住正方形(当您只想执行按距离排序之类的操作时很有用,则可以使用效率更高的

If you can live with just the square (which is useful when you just want to do something like sort by distance, you can use the much more efficient

double dx = (x2-x1);
double dy = (y2-y1);
double dist = dx*dx + dy*dy;

这些将至少与解决方案的效果一样好.在最坏的情况下,pow()将使用堆栈并且效率较低,但是在这种情况下,也许您的编译器会将其转换为x * x.

These will be at least as good as a solution pow. At worst, pow() will use the stack and be less efficient, but maybe your compiler turns it into x*x for this case.

这篇关于计算两个CGPoint之间距离的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆