0

I made a simple linear equation system solver using NumPy arrays. I have two arrays on hand: a 2x2 (A) one and a 2x1 one (B).

By inverting the first one using Ainv = np.linalg.inv(A) and then multiplying it with the second one using Ainv.dot(B), I get a third 2x1 array with my desired x and y values, which is returned by the function, called solveLin() by the way.

Now if I print out print(solveLin()) with the variables in place, I do get the array [[-8.] [ 5.]] with the correct values.

However, if I target the values with print(solveLin()[0][0]) for example, I get -7.999999999999998 and 4.999999999999999 as my answers.

If I set them to display as integers, they become -7 and 4

Edit: I do understand why floating numbers act this way, but I do not understand why are they displayed one way in the array and then another way when called directly.

toshkeen
  • 3
  • 2
  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – ForceBru Mar 30 '19 at 19:26
  • @ForceBru then I do not understand why does it display the values differently in the array. – toshkeen Mar 30 '19 at 19:28
  • that's because NumPy tries to show these imprecise values in a user-friendly way – ForceBru Mar 30 '19 at 19:38

2 Answers2

0

Numpy is trying to be helpful and print things readable. See this for a long explanation of what it's doing.

Printing in python calls str and str is not expected to print precise things, just informative. repr() is for precise representations.

Mihai Andrei
  • 1,024
  • 8
  • 11
0

It is due to, fundamentally, the fact that binary, which is what numpy uses to crunch numbers, is difficult to precisely represent in decimal and vice-versa. Look at how we are used to representing one-third in decimal, 0.33333333.. In python, 0.1 is 0.100000000000000005551115123125.. Here is a link from python docs on the matter : Decimal fixed point and floating point arithmetic

BigH
  • 340
  • 4
  • 6