Numpy: calculate based on previous element?

后端 未结 5 2430
北恋
北恋 2021-02-08 15:45

Say that I have array x and y:

x = numpy.array([1,2,3,4,5,6,7,8,9,10])  # actual content is the a result of another calculation step
         


        
5条回答
  •  天命终不由人
    2021-02-08 16:28

    Lets build a few of the items in your sequence:

    y[0] = 2*y[-1] + x[0]
    y[1] = 2*y[0] + x[1] = 4*y[-1] + 2*x[0] + x[1]
    y[2] = 2*y[1] + x[2] = 8*y[-1] + 4*x[0] + 2*x[1] + x[2]
    ...
    y[n] = 2**(n+1)*y[-1] + 2**n*x[0] + 2**(n-1)*x[1] + ... + x[n]
    

    It may not be immediately obvious, but you can build the above sequence with numpy doing something like:

    n = len(x)
    y_1 = 50
    pot = 2**np.arange(n-1, -1, -1)
    y = np.cumsum(pot * x) / pot + y_1 * 2**np.arange(1, n+1)
    >>> y
    array([  101,   204,   411,   826,  1657,  3320,  6647, 13302, 26613, 53236])
    

    The down side to this type of solutions is that they are not very general: a small change in your problem may render the whole approach useless. But whenever you can solve a problem with a little algebra, it is almost certainly going to beat any algorithmic approach by a far margin.

提交回复
热议问题