1

I was running the same algorithm using python and Matlab. When they solve the same linear system, the results are slightly different, which will lead to a total different results in the end. I am wondering how to fix python to get the same result as Matlab. Thanks!

Ax=b, python:

A=[[ 1.,  0.,  0.,  0.,  1.,  1.,  1.,  2.],
   [ 0.,  0.,  0.,  0., -0., -1., -0., -0.],
   [ 0.,  0.,  0.,  0., -0., -0., -1., -0.],
   [ 0.,  0.,  0.,  0., -0., -0., -0., -1.],
   [ 1., -0., -0., -0., -1., -0., -0., -0.],
   [ 1., -1., -0., -0., -0., -1., -0., -0.],
   [ 1., -0., -1., -0., -0., -0., -1., -0.],
   [ 2., -0., -0., -1., -0., -0., -0., -1.]]
b=[[ 1.],[ 0.],[ 0.],[ 0.],[-1.],[ 0.],[ 0.],[ 0.]]

res_py = numpy.linalg.solve(A,b)

and Matlab:

res_m  = A\b 

The python output:

[[-0.],[ 0.],[ 0.],[-0.],[-1.],[ 0.],[ 0.],[ 0.]]

The Matlab output:

[ 0; -4.163336342344337e-17; -4.163336342344337e-17; 0; -1.000000000000000e+00; 0; 2.775557561562891e-17; 0]
FRANK Zhu
  • 11
  • 1
  • Maybe Matlab is wrong. Indeed non zero values are really small, it might be numerical rounding issue. – Chelmy88 Aug 18 '19 at 23:00
  • 3
    If these small differences lead to totally different results later, it is what you do later that’s wrong. Computations need to take limited precision of float operations into account. – Cris Luengo Aug 19 '19 at 01:10
  • 1
    I'm also not convinced that python doesn't have similar precision differences here but just isn't showing them. The negative 0 output is suspect. – jodag Aug 19 '19 at 02:11
  • 1
    `-4.163336342344337e-17` is `0` – Ander Biguri Aug 19 '19 at 11:09
  • @jodag that is true. Simply python is chosing to display it as zero – Ander Biguri Aug 19 '19 at 11:10

1 Answers1

0

It is possible that Matlab uses higher-precision floating point numbers than your Python script, or uses a different floating precision mode (e.g. fast vs strict).

In most cases, having the result be off by x*10-17 will not result in much trouble - it takes a number of operations for an error of that scale to build up to something significant.

You can also try forcing exponential notation when printing your values to see if they really are rounded (usual stuff).

YellowAfterlife
  • 2,967
  • 1
  • 16
  • 24