求两个数的平方和的平方根的最有效方法是什么? [英] What is the most efficient way of doing square root of sum of square of two numbers?

查看:748
本文介绍了求两个数的平方和的平方根的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种更有效,最短的方法来执行两个或多个数字的平方和的平方根.我实际上正在使用numpy和以下代码:

I am looking for the more efficient and shortest way of performing the square root of a sum of squares of two or more numbers. I am actually using numpy and this code:

np.sqrt(i**2+j**2)

这似乎比以下速度快五倍:

That seems five time faster than:

np.sqrt(sum(np.square([i,j])))

(i和j代表数字!)

我想知道是否已经有一个内置函数可以用更少的代码来更有效地执行这一非常常见的任务.

I was wondering if there was already a built-in function more efficient to perform this very common task with even less code.

推荐答案

对于i != j,不可能使用np.linalg.norm进行此操作,因此我建议以下内容:

For the case of i != j it is not possible to do this with np.linalg.norm, thus I recommend the following:

(i*i + j*j)**0.5

如果ij是单个浮点,则这比np.sqrt(i**2+j**2)快5倍.如果ij是numpy数组,则速度要快20%(由于用i*ij*j替换了正方形.如果不替换正方形,则性能等于np.sqrt(i**2+j**2).
使用单个浮点数的一些时间安排:

If i and j are single floats, this is about 5 times faster than np.sqrt(i**2+j**2). If i and j are numpy arrays, this is about 20% faster (due to replacing the square with i*i and j*j. If you do not replace the squares, the performance is equal to np.sqrt(i**2+j**2).
Some timings using single floats:

i = 23.7
j = 7.5e7
%timeit np.sqrt(i**2 + j**2)
# 1.63 µs ± 15.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit (i*i + j*j)**0.5
# 336 ns ± 7.38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%timeit math.sqrt(i*i + j*j)
# 321 ns ± 8.21 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

math.sqrt(i*i + j*j)**0.5快一点,但是以牺牲灵活性为代价:(i*i + j*j)**0.5将在单个浮点AND数组上工作,而math.sqrt仅在标量.

math.sqrt is slightly faster than (i*i + j*j)**0.5, but this comes at the cost of losing flexibility: (i*i + j*j)**0.5 will work on single floats AND arrays, whereas math.sqrt will only work on scalars.

中型阵列的一些时间安排:

And some timings for medium-sized arrays:

i = np.random.rand(100000)
j = np.random.rand(100000)
%timeit np.sqrt(i**2 + j**2)
# 1.45 ms ± 314 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit (i*i + j*j)**0.5
# 1.21 ms ± 78.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

这篇关于求两个数的平方和的平方根的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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