0

# expected w and y to have the same length

Package:
numpy
17141
Exception Class:
TypeError

## Raise code

``````    # apply weighting
if w is not None:
w = NX.asarray(w) + 0.0
if w.ndim != 1:
raise TypeError("expected a 1-d array for weights")
if w.shape[0] != y.shape[0]:
raise TypeError("expected w and y to have the same length")
lhs *= w[:, NX.newaxis]
if rhs.ndim == 2:
rhs *= w[:, NX.newaxis]
else:
rhs *= w

# scale lhs to improve condition number and solve``````

## Ways to fix

2

The function numpy.polyfit is used to tit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y).

usage:

```z = np.polyfit(x, y, deg,w=wight)
```

Here w(wight) specifies the weights to apply to the y-coordinates of the sample points. And it is expected that the weight array have the same length as the y array.

Reproducing the error:

```import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) # y has a length of 6
w = np.array([0.4,1,3.1,5,1,4,2]) # w has a length of 7 (incompatible with y)
z = np.polyfit(x, y, 3,w=w)
print(z)
```

Fix:

```import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
w = np.array([0.4,1,3.1,5,1,4,])
z = np.polyfit(x, y, 3,w=w)
print(z)
```

Jun 11, 2021
kellemnegasi 2.7k