Home > OS >  Python shape (ValueError) error when trying to compute a derivative with numpy - diff
Python shape (ValueError) error when trying to compute a derivative with numpy - diff

Time:12-06

I'm interested on calculating a derivative using diff from numpy. For this, I use two arrays a and b with shape (N,) try to compute x

N=int(1e4)
a=np.ones(N)
b=9*np.ones(N)

x=np.zeros((N,1)) #shape (10000, 1)
for j in range(N):
    x[j]=a[j]/b[j]
y=3*x - 1

doty=np.diff(y)/np.diff(b)

I find a ValueError: operands could not be broadcast together with shapes (10000,0) (9999,).

Why does this happens? How can I reshape b to match x?

CodePudding user response:

Try this:

doty = np.diff(y.reshape(-1)) / np.diff(b)
  • Related