## Numpy如何调用单函数的均值和方差？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (78)

### 2 个回答

```In [329]: a = np.random.rand(1000)

In [330]: %%timeit
.....: a.mean()
.....: a.var()
.....:
10000 loops, best of 3: 80.6 µs per loop

In [331]: %%timeit
.....: m = a.mean()
.....: np.mean((a-m)**2)
.....:
10000 loops, best of 3: 60.9 µs per loop

In [332]: m = a.mean()

In [333]: a.var()
Out[333]: 0.078365856465916137

In [334]: np.mean((a-m)**2)
Out[334]: 0.078365856465916137```

```In [335]: np.dot(a-m,a-m)/a.size
Out[335]: 0.078365856465916137

In [336]: %%timeit
.....: m = a.mean()
.....: c = a-m
.....: np.dot(c,c)/a.size
.....:
10000 loops, best of 3: 38.2 µs per loop```

```In [7]: import numpy as np

In [8]: a = np.random.rand(1000)

In [9]: %%timeit
...: a.mean()
...: a.var()
...:
10000 loops, best of 3: 24.7 us per loop

In [10]: %%timeit
...: m = a.mean()
...: np.mean((a-m)**2)
...:
100000 loops, best of 3: 18.5 us per loop

In [11]: %%timeit
...: m = a.mean()
...: power = np.mean(a ** 2)
...: power - m ** 2
...:
100000 loops, best of 3: 17.3 us per loop

In [12]: %%timeit
...: m = a.mean()
...: power = np.dot(a, a) / a.size
...: power - m ** 2
...:
100000 loops, best of 3: 9.16 us per loop```