2

The code below is used to calculate the inner product of two vectors, but sometimes it returns wrong values and I don't know why. Can anyone help me with this problem?

Specifically for these inputs: [-2.328, -7.284, -1.214] and [-1.821, 1.072, -2.94]

reduce(lambda x,y : x+y, [x*y for x,y in zip(self.coordinates, v.coordinates)])
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 2
    Why not just: `sum(x*y for x,y in zip(self.coordinates, v.coordinates))`. Give an example of the dataset that gives wrong results. – Moses Koledoye Aug 11 '17 at 09:34
  • 1
    You should take a look at [`np.inner`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.inner.html). – Michael H. Aug 11 '17 at 09:35
  • that works the same. You know both of them return wrong answers when I use them to calculate the inner product of the vectors: [-2.328, -7.284, -1.214] and [-1.821, 1.072, -2.94] @MosesKoledoye – Amirhossein Aug 11 '17 at 09:37
  • thank you, but I was trying to implement this method myself as a part of linear algebra course at udacity.com @Michael – Amirhossein Aug 11 '17 at 09:39

1 Answers1

4

My guess is that this is a rounding error. Using the vectors in your example:

a = [-2.328, -7.284, -1.214]
b = [-1.821, 1.072, -2.94]
c = reduce(lambda x,y : x+y, [x*y for x,y in zip(a, b)])
print(c)

will give -1.3322676295501878e-15 while the real result should be 0. For comparison the numpy function np.inner(a,b) will give a very similar result; -1.33226762955e-15.

The error is due to that any number that can't be built from exact powers of two can't be represented exactly as a floating point number and needs to be approximated. For more in-depth information you can read: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Shaido
  • 27,497
  • 23
  • 70
  • 73