取矢量的功率有效的方式 [英] efficient way to take powers of a vector
问题描述
我写了一个code,它采用数字勒让德多项式高达一些高n阶。例如:
I wrote a code that numerically uses Legendre polynomials up to some high n-th order. For example:
....
case 8
p = (6435*x.^8-12012*x.^6+6930*x.^4-1260*x.^2+35)/128; return
case 9
...
如果向量 X
长此会变慢。我看到有 X ^ 4
和 X之间说一个的性能差异。* X,* X * X
,我想我可以用它来改善我的code。我使用 timeit
,发现了:
If the vectorx
is long this can become slow. I saw that there is a performance difference between say x.^4
and x.*x.*x.*x
and thought I could use this to improve my code. I've used timeit
and found that for:
x=linspace(0,10,1e6);
f1= @() power(x,4)
f2= @() x.4;
f3= @() x.^2.^2
f4= @() x.*x.*x.*x
F4
为更快由因子2 比其他人。然而,当我去 X ^ 6
有之间的差异很小为(x,* X * X)^ 2
和 X。* X,* X,* X,* X * X
(而所有其他选项都是慢)。
f4
is faster by a factor 2 than the rest. However when I go to x.^6
there is very little difference between (x.*x.*x).^2
and x.*x.*x.*x.*x.*x
(while all other options are slower).
有没有去告诉这将是采取矢量的功率最有效的方法是什么?
你能解释为什么在性能如此大的差异?
Is there away to tell what will be the most efficient way to take a power of a vector? Can you explain why there is such a big difference in performance?
推荐答案
这是不完全回答你的问题,但它可能会解决你的问题:
This is not exactly an answer to your question, but it may solve your problem:
x2 = x.*x; % or x.^2 or power(x,2), whichever is most efficient
p = ((((6435*x2-12012)*x2+6930)*x2-1260)*x2+35)/128
这样,你做电源只有一次,并只与指数2.这招可以应用到所有的勒让德多项式(在奇数阶多项式有一个 X2
是通过替换X
)。
这篇关于取矢量的功率有效的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!