作为一个替代选择(对于那些感兴趣的人),如果想要 R 中 seq(start, end, by, length.out)
函数的功能,下面的函数提供了完整的功能。
def seq(start, end, by = None, length_out = None):
len_provided = True if (length_out is not None) else False
by_provided = True if (by is not None) else False
if (not by_provided) & (not len_provided):
raise ValueError('At least by or length_out must be provided')
width = end - start
eps = pow(10.0, -14)
if by_provided:
if (abs(by) < eps):
raise ValueError('by must be non-zero.')
#Switch direction in case in start and end seems to have been switched (use sign of by to decide this behaviour)
if start > end and by > 0:
e = start
start = end
end = e
elif start < end and by < 0:
e = end
end = start
start = e
absby = abs(by)
if absby - width < eps:
length_out = int(width / absby)
else:
#by is too great, we assume by is actually length_out
length_out = int(by)
by = width / (by - 1)
else:
length_out = int(length_out)
by = width / (length_out - 1)
out = [float(start)]*length_out
for i in range(1, length_out):
out[i] += by * i
if abs(start + by * length_out - end) < eps:
out.append(end)
return out
这个函数比 numpy.linspace
慢一点(大约慢4倍-5倍),但是使用 numba,我们可以获得一个速度大约快2倍的函数,并保持与 R 相同的语法。
from numba import jit
@jit(nopython = True, fastmath = True)
def seq(start, end, by = None, length_out = None):
[function body]
我们可以像在 R 中执行一样来执行这个操作。
seq(0, 5, 0.3)
在上述实现中,它也允许在“by”和“length_out”之间进行一定程度的交换。
seq(0, 5, 10)
#out: [0.0,
0.5555555555555556,
1.1111111111111112,
1.6666666666666667,
2.2222222222222223,
2.7777777777777777,
3.3333333333333335,
3.8888888888888893,
4.444444444444445,
5.0]
基准测试:
%timeit -r 100 py_seq(0.5, 1, 1000) #Python no jit
133 µs ± 20.9 µs per loop (mean ± std. dev. of 100 runs, 1000 loops each)
%timeit -r 100 seq(0.5, 1, 1000) #adding @jit(nopython = True, fastmath = True) prior to function definition
20.1 µs ± 2 µs per loop (mean ± std. dev. of 100 runs, 10000 loops each)
%timeit -r 100 linspace(0.5, 1, 1000)
46.2 µs ± 6.11 µs per loop (mean ± std. dev. of 100 runs, 10000 loops each)
numpy.linspace
吗? - celnumpy.arange
文档在“参见”部分中提到了numpy.linspace
,这非常有帮助。每当您正在寻找执行类似或相关于您已知函数的功能的函数时,请查看该部分。 - user2357112np.r_
的切片索引语法,将虚数作为“步长”参数,例如np.r_[1:1.5:10j]
。 - ali_m