Python Forum

Full Version: Inaccurate result when a vector is divided by a matrix
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm relatively new in Python, I did a lots of programs in Octave but now try to transfer them in PyThon.
One of my program divide a vector by a matrix, strangely the results is very different from the one I
obtain from Octave. The Octave results looks OK because the output final result is in accordance with the real
result of the publish examples.

The Python program (reduce to the essential)
import numpy as np
a=np.array([10,10,10])
b=np.array([[1,1,1],[2,2,2],[3,3,3]])
print(a)
print(b)
c=np.divide(a,b)
print("np.divide(a,b) = ")
print (c)
The Python results:
Output:
[10 10 10] [[1 1 1] [2 2 2] [3 3 3]]
np.divide(a,b) =
Output:
[[10. 10. 10. ] [ 5. 5. 5. ] [ 3.33333333 3.33333333 3.33333333]]
The Octave results for the same operation:
Output:
0.71429 , 1.42847 , 2.14286
I Try different configuration of the vector (horizontal,Vertical)
Thanks for your help
Dennis
Why do you use np.divide instead of c = a / b? Numpy array/ndarray class override standard (magic) Python methods and you can use
usual arithmetic operators, e.g. +, *, /, @ -- for matrix multiplication (row-by-column fashion).
I worked with MatLab for a long time ago, but it seems to me that a/b gives a solution of a system of linear equations in octave/matlab, e.g. it returns x, where b*x = a or something similar( I am not sure exactly). Maybe it returns a minimal norm solution in a least-squares sense. So, in Octave you got a solution of a SLAE (system of linear algebraic equations)
defined by corresponding matrices a and b. Consider using ./ in octave for element-wise division (not sure, however).
I should have mention it, I did try c=a/b on Python but I get the same result. As I said the result on Octave is the right one.
Ok,
if you try to execute the following code
import numpy as np
a = np.array([10, 10, 10])
b = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])
a @ np.linalg.pinv(b)
you get
Output:
array([0.71428571, 1.42857143, 2.14285714])
np.linalg.pinv(x) returns Moore-Penrose inversion of a matrix x. x @ y denotes matrix product between x and y. Moore-Penrose inversion is used to obtain least squares solution for over-determined (or under-determined) linear systems. Octave knows: if you are trying to divide one matrix onto another, you are likely trying to solve system of linear equations. E.g.: Ax=b, then x = b / A; in Python you should do this: x = np.linalg.pinv(A) @ b.