使用泰勒级数来加速计算

Use of Taylor series to speed up computation

在数学中,Taylor series 对于小阶多项式的函数逼近很重要。

我想看看这样的近似值有何帮助,例如为了加快计算速度。让我们使用著名的泰勒级数:

log(1+x) = x + 0.5 * x^2 + (error term)

从道德上讲,计算 2 次多项式的值应该比计算 log.

快得多

因此测试这个的代码:

import numpy, time

def f(t):
    return t + 0.5 * t ** 2
f = numpy.vectorize(f)  

s = time.time()
for i in range(100):
    x = numpy.random.rand(100000) 
    numpy.log(1 + x)
print time.time() - s          # 0.556999921799 seconds

s = time.time()
for i in range(100):
    x = numpy.random.rand(100000)
    f(x)
print time.time() - s          # arghh! 4.81500005722 seconds

为什么多项式方法比实际日志慢10倍?我预料的恰恰相反。

PS:这道题大概在SO和math.SE中间。

使用 numpy 的矢量化操作几乎总是比您自己的代码中任何尝试的优化更快。正如@Divakar 所提到的,vectorize 实际上只是编写 for 循环的一种便捷方式,因此您的代码将比 numpy 的本机代码慢。

将 numpy 的优化例程替换为标准 python 代码表明您的方法速度大致相同。

import math, numpy, time


def f(t):
    return t + 0.5 * t ** 2

x = numpy.random.rand(1000000)

s = time.time()
for num in x:
    math.log(1 + num)
print (time.time() - s  )  

s = time.time()
for num in x:
    f(num)
print (time.time() - s)      

结果:

1.1951053142547607
1.3485901355743408

逼近只是稍微慢一点,但取幂非常昂贵。用 t*t 替换 t ** 2 得到了很好的改进,并允许近似值略微优于 python 的 log

1.1818947792053223
0.8402454853057861

编辑:或者,由于这里的重要教训是优化的科学库几乎在一周的任何一天都优于手动编码的解决方案,这里是使用 numpy 的矢量化操作的泰勒级数近似,这是迄今为止最快的。请注意,唯一的大变化是 vectorize 未在近似函数上调用,因此默认使用 numpy 的向量化运算。

import numpy, time

def f(t):
    return t + 0.5 * t ** 2

x = numpy.random.rand(1000000)
s = time.time()
numpy.log(1 + x)
print (time.time() - s)

s = time.time()
x = numpy.random.rand(100000)
f(x)
print (time.time() - s  )

结果:

0.07202601432800293
0.0019881725311279297

你知道了,矢量化近似比 numpy 的矢量化快了一个数量级 log

使用 Python+Numpy,它可能在这里和那里进行了优化,因此不可能真正对 log(1+x)x + 0.5 * x^2 进行基准测试。 所以我转向了 C++。

结果:

Time per operation with log: 19.57 ns
Time per operation with order-2 Taylor expansion of log: 3.73 ns

大约是 x5 倍!


#include <iostream>
#include <math.h>
#include <time.h>
#define N (1000*1000*100)
#define NANO (1000*1000*1000)

int main()
{
  float *x = (float*) malloc(N * sizeof(float));
  float y;
  float elapsed1, elapsed2;
  clock_t begin, end;
  int i;

  for (i = 0; i < N; i++) 
    x[i] = (float) (rand() + 1) / (float)(RAND_MAX);

  begin = clock();
  for (i = 0; i < N; i++) 
    y = logf(x[i]);
  end = clock();
  elapsed1 = float(end - begin) / CLOCKS_PER_SEC / N * NANO;

  begin = clock();
  for (i = 0; i < N; i++) 
    y = x[i] + 0.5 * x[i] * x[i];  
  end = clock();
  elapsed2 = float(end - begin) / CLOCKS_PER_SEC / N * NANO;

  std::cout << "Time per operation with log: " << elapsed1 << " ns\n";  
  std::cout << "Time per operation with order-2 Taylor epansion: " << elapsed2 << " ns";

  free(x);

}