Q:

Python: fast residuals computing

What is the most efficient way to compute the residuals of two numpy arrays?
I'm doing this the next way:
def residuals(array1, array2):
sum = 0.
for i in xrange(len(lane1)):
    sum += (lane1[i] - lane2[i])**2
return sum

And I'm wondering if there is any other better solutions?

A:

Yes, note that you can perform mathematical operations directly on arrays and they are applied element-wise:
>>> import numpy as np
>>> arr1 = np.array((1, 2, 3))
>>> arr2 = np.array((4, 5, 6))
# differences
>>> arr1 - arr2
array([-3, -3, -3])
# squared differences
>>> (arr1 - arr2) ** 2
array([9, 9, 9])
# sum of squared differences
>>> np.sum((arr1 - arr2) ** 2)
27

