简体   繁体   English

如何在 numpy.nditer 中指定开始和步长?

[英]How can I specify start and step size in numpy.nditer?

I have the following Python code which computes the first n Euler Totient function values:我有以下 Python 代码,它计算第一个n Euler Totient function 值:

import numpy as np

def euler_totients(n):
    phi = np.arange(n+1)

    it = np.nditer(phi, flags=['f_index'])
    for i in it:
        if i == it.index and it.index > 1:
            for j in range(it.index, n+1, it.index):
                phi[j] -= phi[j] / it.index

    return phi

I would like to use numpy.nditer for the inner loop but it doesn't appear to allow specification of the starting point or the step size as I need for the inner loop.我想将numpy.nditer用于内循环,但它似乎不允许指定内循环所需的起点或步长。 The official documentation for numpy.nditer includes a brief description of the itershape parameter (which sounds promising), but it's a bit vague and doesn't include an example. numpy.nditer 的官方numpy.nditer包括对itershape参数的简要描述(这听起来很有希望),但它有点含糊,没有包含示例。

So, is there a way I can specify the starting point and step size of an numpy.nditer and if so, how?那么,有没有办法可以指定numpy.nditer的起点和步长,如果可以,如何?

Plain python version is faster:普通版 python 版本更快:

In [166]: def foo(n):
     ...:     phi = list(range(n+1))
     ...:     for index,i in enumerate(phi):
     ...:        if i==index and index>1:
     ...:            for j in range(index, n+1, index):
     ...:               phi[j] -= int(phi[j]/index)
     ...:     return phi
     ...: 
In [167]: foo(10)
Out[167]: [0, 1, 1, 2, 2, 4, 2, 6, 4, 6, 4]
In [168]: timeit euler_totients(1000)
15.7 ms ± 63.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [169]: timeit foo(1000)   
637 µs ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM