numpy (matrix solver) - python vs. matlab

Kiuhnm kiuhnm03.4t.yahoo.it
Sun Apr 29 18:39:25 EDT 2012


On 4/30/2012 0:17, someone wrote:
> Hi,
>
> Notice cross-post, I hope you bear over with me for doing that (and I
> imagine that some of you also like python in the matlab-group like
> myself)...
>
> ------------------------------------------
> Python vs. Matlab:
> ------------------------------------------
>
> Python:
> ========
> from numpy import matrix
> from numpy import linalg
> A = matrix( [[1,2,3],[11,12,13],[21,22,23]] )
> print "A="
> print A
> print "A.I (inverse of A)="
> print A.I
>
> A.I (inverse of A)=
> [[ 2.81466387e+14 -5.62932774e+14 2.81466387e+14]
> [ -5.62932774e+14 1.12586555e+15 -5.62932774e+14]
> [ 2.81466387e+14 -5.62932774e+14 2.81466387e+14]]
>
>
> Matlab:
> ========
>  >> A=[1 2 3; 11 12 13; 21 22 23]
>
> A =
>
> 1 2 3
> 11 12 13
> 21 22 23
>
>  >> inv(A)
> Warning: Matrix is close to singular or badly scaled.
> Results may be inaccurate. RCOND = 1.067522e-17.
>
> ans =
>
> 1.0e+15 *
>
> 0.3002 -0.6005 0.3002
> -0.6005 1.2010 -0.6005
> 0.3002 -0.6005 0.3002
>
> ------------------------------------------
> Python vs. Matlab:
> ------------------------------------------
>
> So Matlab at least warns about "Matrix is close to singular or badly
> scaled", which python (and I guess most other languages) does not...

A is not just close to singular: it's singular!

> Which is the most accurate/best, even for such a bad matrix? Is it
> possible to say something about that? Looks like python has a lot more
> digits but maybe that's just a random result... I mean.... Element 1,1 =
> 2.81e14 in Python, but something like 3e14 in Matlab and so forth -
> there's a small difference in the results...

Both results are *wrong*: no inverse exists.

> With python, I would also kindly ask about how to avoid this problem in
> the future, I mean, this maybe means that I have to check the condition
> number at all times before doing anything at all ? How to do that?

If cond(A) is high, you're trying to solve your problem the wrong way. 
You should try to avoid matrix inversion altogether if that's the case. 
For instance you shouldn't invert a matrix just to solve a linear system.

Kiuhnm



More information about the Python-list mailing list