How can I calculate the 1-norm of the difference of two vectors, ||a - b||_1 = sum(|a_i - b_i|)
in Python?
a = [1,2,3,4]
b = [2,3,4,5]
||a - b||_1 = 4
How can I calculate the 1-norm of the difference of two vectors, ||a - b||_1 = sum(|a_i - b_i|)
in Python?
a = [1,2,3,4]
b = [2,3,4,5]
||a - b||_1 = 4
You appear to be asking for the sum of the differences between the paired components of the two arrays:
>>> A=[1,2,3,4]
>>> B=[2,3,4,5]
>>> sum(abs(a - b) for a, b in zip(A, B))
4
As people said no idea what are you doing here, so here is my gues too at least get that answer using that data
a=[1,2,3,4]
b=[2,3,4,5]
def a_b(a,b):
return sum(map(lambda a:abs(a[0]-a[1]), zip(a,b)))
print a_b(a,b)
Python has powerful built-in types, but Python lists are not mathematical vectors or matrices. You could do this with lists, but it will likely be cumbersome for anything more than trivial operations.
If you find yourself needing vector or matrix arithmetic often, the standard in the field is NumPy, which probably already comes packaged for your operating system the way Python also was.
I share the confusion of others about exactly what it is you're trying to do, but perhaps the numpy.linalg.norm function will help:
>>> import numpy
>>> a = numpy.array([1, 2, 3, 4])
>>> b = numpy.array([2, 3, 4, 5])
>>> numpy.linalg.norm((a - b), ord=1)
4
To show how that's working under the covers:
>>> a
array([1, 2, 3, 4])
>>> b
array([2, 3, 4, 5])
>>> (a - b)
array([-1, -1, -1, -1])
>>> numpy.linalg.norm((a - b))
2.0
>>> numpy.linalg.norm((a - b), ord=1)
4
In NumPy, for two vectors a
and b
, this is just
numpy.linalg.norm(a - b, ord=1)