A. chbihi - 4 months ago 26

Python Question

I am trying to compute the norm L2 error between two arrays y1 and y2. However, my two arrays have different sizes.

`x1 = np.array([0 , 0.1 , 0.2 , 0.3 , 0.4 , 0.5])`

y1 = np.array([0 , 2 , 2 , 3 , 4 , 6])

x2 = np.array([0 , 0.1 , 0.2 , 0.3 , 0.4])

y2 = np.array([0 , 2 , 2 , 3 , 4])

L2_error = np.linalg.norm(y1-y2)

ValueError: operands could not be broadcast together with shapes (5) (6)

My idea is to perform an interpolation according to the x array with the greater size (in my case: x1). So I will find a sixth element for x2 and y2, then I could compute my error.

Does anyone have an efficient tool to do this in Python?

Thank you

Answer

You could try using `itertools.zip_longest`

and fill the shorter sequence links with a default value:

https://docs.python.org/3.3/library/itertools.html?highlight=zip#itertools.zip_longest

For example:

```
>>> from itertools import *
>>> lst = zip_longest(range(10),
... range(9),
... fillvalue=None)
>>> lst
... [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, None)]
>>> for x, y in lst:
... if None not in [x, y]:
... compute(x, y)
...
```