0

As mentioned in Zero pad numpy array, this function zero pads an array:

A = np.array([1,2,3,4,5])
B = np.pad(A, (0, 3), 'constant')   # array([1, 2, 3, 4, 5, 0, 0, 0])

Question: Is there a helper function in numpy or scipy that automatically zero pads an array to the next power-of-2 size? (Useful for FFT purposes, etc.)

Of course I can do something like

def padpower2(A):
    return np.pad(A, (0, int(2**np.ceil(np.log2(len(A)))) - len(A)), 'constant')

but it's alway tricky to remember/rewrite, so having a ready-to-use numpy function would be better.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • It's too specialized to be part of `numpy`. If it is particular useful for FFT, there might be something in the `scipy.signal` module, or where ever FFT is implement. But most likely you'll have to write your own utility. – hpaulj Nov 10 '20 at 08:05
  • I'm not aware of any numpy built-in that can do this. Regarding the computation of the next power of 2, `1 << (x - 1).bit_length()` is a more efficient approach. – GZ0 Nov 10 '20 at 08:20
  • Good to know @GZ0. Feel free to post an answer with this helpful trick! – Basj Nov 10 '20 at 08:23

0 Answers0