Recurrence with numpy

前端 未结 4 918
广开言路
广开言路 2020-12-20 03:14

Is there any way to make recurrence without using for\'s in numpy?

Using np.add with out keyword do the trick with dtype=\"int\"

4条回答
  •  暖寄归人
    2020-12-20 03:32

    Since linear recurrences have analytic solutions (here for Fibonacci), an other rapid scipy method is :

    def fib_scipy2(N):
        r5=math.sqrt(5)
        phi=(1+r5)/2
        a= (-phi*ones(N)).cumprod()
        return (np.abs(a)-1/a)/r5
    

    Runs :

    In [413]: fib_scipy2(8)
    Out[413]: array([  1.,   1.,   2.,   3.,   5.,   8.,  13.,  21.])
    In [414]: %timeit fib(10**4)
    103 µs ± 888 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    You can tune it to any linear equation.

提交回复
热议问题