0

I have to draw plot using least squares method in Python 3. I have list of x and y values:

y = [186,273,308,484]
x = [2.25,2.34,2.47,2.56] 

There are many more values for x and for y, there is only a shortcut. And now, I know, that f(x)=y should be a linear function. I can get cofactor „a” and „b” of this function, by calculating:

 delta_x  = x[len(x)]-x[0] and delta_y = y[len(y)]-y[0]

Etc, using tangent function. I know, how to do it. But there are also uncertainties of y, about 2 percent of y. So I have y_errors table, which contains all uncertainties of y.

But what now, how I can draw least squares? Of course I have been used Google, I saw docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#least-square-fitting-leastsq, but there are some problems.
I tried to edit example from scipy.org to my own purpose. So I edited x, y, y_meas variables, putting here my own lists. But now, I dont know, what is p0 variable in this example. And what should I must edit to make my example working.

Of course I can edit also residuals function. It must get only one variable - y_true. In addition to this I dont understand arquments of leastsq function. Sorry for my english and for asking such newbie question. But I dont understand this method. Thank You in advance.

1 Answers1

0

I believe you are trying to fit a set of {x, y} (and possibly sigma_y: the uncertainties in y) values to a linear expression. This is known as linear regression, and For linear regression (or indeed, for regression of any polynomial) you can use numpy's polyfit. The uncertainties can be used for the weights::

weight = 1/sigma_y

where sigma_y is the standard deviation in y.

The least-squares routines in scipy.optimize allow you to fit a non-linear function to data, but you have to write the function that computes the "residual" (data - model) in terms of variables that are to be adjusted in order to minimize the calculated residual.