给定 r^2,有没有一种有效的方法来计算 r^3?
double r2 = dx * dx + dy * dy;
double r3 = r2 * sqrt(r2);
第二行可以用更快的东西代替吗?不涉及 sqrt
的东西?
double r2 = dx * dx + dy * dy;
double r3 = r2 * sqrt(r2);
Can the second line be replaced by something faster? Something that does not involve sqrt
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
。
如果 sqrt 是作为 pow 的特殊情况实现的,那将节省您的乘法运算 在宏伟的计划中并没有太多的想法!
如果您确实寻求更高的效率,请考虑是否确实需要 r^3。例如,如果您只是测试它(或从它派生的东西)以查看它是否超过某个阈值,则测试 r2 例如,
这样
pow
将仅被调用一次,甚至可能在编译时间。编辑如果您确实需要每次重新计算阈值,我认为有关 Q_rsqrt 的答案值得一看,并且可能值得超过这个答案
How about
If sqrt is implemented as a special case of pow, that will save you a multiplication. Not much in the grand scheme of things mind!
If you are really looking for greater efficiency, consider whether you really need r^3. If, for example, you are only testing it (or something derived from it) to see whether it exceeds a certain threshold, then test r2 instead e.g.
That way
pow
will be called only once, maybe even at compile time.EDIT If you do need to recompute the threshold each time, I think the answer concerning Q_rsqrt is worth a look and probably deserves to outrank this one
使用快速反平方根(采用
Q_rsqrt
函数)。您有:
注意:对于
double
类型,有一个像0x5f3759df
这样的常量,它可以帮助您编写一个也处理double<的函数/code> 数据类型。
稍后编辑:似乎已经讨论过该方法这里。
后来的编辑2:
double
的常量在维基百科中 链接:Use fast inverse sqrt (take the
Q_rsqrt
function).You have:
NOTE: For
double
types there is a constant like0x5f3759df
which can help you write a function that handles alsodouble
data types.LATER EDIT: Seems like the method has been already discussed here.
LATER EDIT2: The constant for
double
was in the wikipedia link:我认为看待你的问题的另一种方式是“如何计算(或近似)sqrt(n)”。从那里你的问题将变得微不足道(n * sqrt(n))。当然,您必须定义可以忍受多少错误。维基百科为您提供了许多选项:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots
I think another way to look at your question would be "how to calculate (or approximate) sqrt(n)". From there your question would be trivial (n * sqrt(n)). Of course, you'd have to define how much error you could live with. Wikipedia gives you many options:
http://en.wikipedia.org/wiki/Methods_of_computing_square_roots