numpy least-squares solution for a matrix with complex elements

71 views Asked by At

I am trying to solve the equation y=a*x. I have three measurements for x (x1,x2,x3) and y (y1,y2,y3) and am trying to find "a" ( the slop). The first important thing is that y and X are complex numbers (e.g., a+ib). When I divide y1/x1 and the rest of the data, I get the correct answer (I already know the answer), but when I use the np.linalg.lstsq(), I get different one. Here is my code:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
y1= -19.64927911-6.1398258j
x1=-1.1754612296645994+1.246124677990216*1j
y2=-(20.362010267083804+5.457126922032681*1j)
x2=-1.1754612296645994+1.246124677990216*1j
y3=-(-21.582640711300716-4.866985215398231*1j)
x3=1.0043723963072644-0.6003393298974578*1j
coeff_1=y1/x1
coeff_2=y2/x2
coeff_3=y3/x3

########linear least square method
X=np.vstack((x1,x2,x3))
Y=np.vstack((y1,y2,y3))

[coeff, resid, _, singular_values] = np.linalg.lstsq(X, Y, rcond=None)
print(coeff_1)
print(coeff_2)
print(coeff_3)
print(coeff)
print(np.abs(coeff_1))
print(np.abs(coeff_2))
print(np.abs(coeff_3))
print(np.abs(coeff))

If you run it, coeff_1 is different from coeff_2 (which is incorrect). Please help me figure this out.

1

There are 1 answers

6
Oskar Hofmann On

I visualized the (complex) values y1/x1, y2/x2 and y3/x3 and the fitted coeficient from your data:

plt.plot((y1/x1).real, (y1/x1).imag, marker = 'o', label = 'y1/x1')
plt.plot((y2/x2).real, (y2/x2).imag, marker = 'o', label = 'y2/x2')
plt.plot((y3/x3).real, (y3/x3).imag, marker = 'o', label = 'y3/x3')
plt.plot(coeff.real, coeff.imag, marker = 'o', label = 'lstsq-fit')
plt.xlabel('real')
plt.ylabel('imag')
plt.legend()
plt.show()

Visualization of data

Your data varies wildly. Why should a least-square-fit with that data give exactly the value y1/x1 ? The leastsquare-fit seems to be nice in the middle of your data.