2016-03-31   python   numpy 

Python練習(総和、平均、分散)

import numpy as np

def sum(a):
    s = 0.0
    for x in a:
        s += x
    return s

def mean(a):
    return sum(a) / len(a)

def var(a, ddof=0):
    m = mean(a)
    v = 0.0
    for x in a:
        v += (x - m) ** 2
    return v / (len(a) - ddof)

np.random.seed(314159)
value = np.random.rand(10000)

print(sum(value))
print(np.sum(value))

print(mean(value))
print(np.mean(value))

print(var(value))
print(np.var(value))

print(var(value, ddof=1))
print(np.var(value, ddof=1))
5054.92326062
5054.92326062
0.505492326062
0.505492326062
0.0847233737255
0.0847233737255
0.0847318469101
0.0847318469101
 2016-03-31   python   numpy