0

I think I should have the same result using both methods (In[4] and In[5]). What's wrong? I can tell the correct is In[5].

In [1]: import numpy as np

In [2]: A = np.mat('1 2 3; 4 5 6; 7 8 9')

In [3]: B = np.mat('10;20;30')

In [4]: A.I*B
Out[4]:
matrix([[ 64.],
        [-64.],
        [ 16.]])

In [5]: np.linalg.solve(A,B)
Out[5]:
matrix([[-0.93333333],
        [ 1.86666667],
        [ 2.4       ]])
Hugo Salvador
  • 1,094
  • 1
  • 11
  • 11
  • 1
    The matrix A = np.mat('1 2 3; 4 5 6; 7 8 9') is singular and doesn't have an inverse. Are you sure you do the right thing? – Boendal Dec 10 '19 at 14:30
  • Side note: [don't use the matrix class](https://stackoverflow.com/questions/53254738/deprecation-status-of-the-numpy-matrix-class). – Andras Deak -- Слава Україні Dec 10 '19 at 14:33
  • 2
    Does this answer your question? [Why does numpy.linalg.solve() offer more precise matrix inversions than numpy.linalg.inv()?](https://stackoverflow.com/questions/31256252/why-does-numpy-linalg-solve-offer-more-precise-matrix-inversions-than-numpy-li) – Boendal Dec 10 '19 at 14:36
  • I would have thought the same thing but the difference between 64 and -0.9 seems a bit extreme for a floating point error – Jamie J Dec 10 '19 at 14:38
  • 1
    The larger problem is that the determinant of the matrix above *should* be 0, but calling `np.linalg.det` on the matrix class, is giving a tiny floating point number, which means that it won't raise on matrix inverse. When I call the same function on the array equivalent I correctly get 0. – user3483203 Dec 10 '19 at 14:43
  • yeah I think so too but if we consider that his code isn't even working then the possibility is quite high that this may answer his question – Boendal Dec 10 '19 at 14:43

1 Answers1

1

Firstly I believe A is singular so this will not work, could you show the actual matrices you are using? I have tested with the following:

A = np.mat('1 0 3; 0 1 2; 0 3 1')   
B = np.mat('10;20;30') 

In [15]: np.linalg.solve(A,B)                                                                                                                                                     
Out[15]: 
matrix([[-8.],
        [ 8.],
        [ 6.]])

In [16]: A.I * B                                                                                                                                                                  
Out[16]: 
matrix([[-8.],
        [ 8.],
        [ 6.]])

And it works

Jamie J
  • 1,168
  • 1
  • 9
  • 22