Ask Your Question

fitting a curve to a straight line

asked 2011-09-23 21:31:50 -0600

ebs gravatar image

updated 2015-01-14 04:01:39 -0600

FrédéricC gravatar image

How can I use sage to fit some points like

x = [1, 3, 4...] y = [1.2, 4.5, 3.6, ...]

to a straight line using method of least squares And make a plot of the points and the line?

edit retag flag offensive close merge delete

4 answers

Sort by » oldest newest most voted

answered 2011-09-24 05:42:48 -0600

Jason Grout gravatar image

Searching in google for "sage least squares" gives three examples as the three top hits. Here is another example:

You can also use scipy to do it:

or numpy:

edit flag offensive delete link more


Or R, naturally.

kcrisman gravatar imagekcrisman ( 2011-09-25 16:09:35 -0600 )edit

answered 2011-09-26 22:31:22 -0600

Joaquim Puig gravatar image

In my opinion the easiest way to do the fit is to use the find_fit function, which is standard in SAGE. For example:

sage: x = [1, 3, 4]   
sage: y = [1.2, 4.5, 3.6]
sage: var('a,b,t')
sage: model(t)=a*t+b
sage: data=zip(x,y)
sage: fit=find_fit(data,model,solution_dict=True) # Dictionary is optional but handy
sage: model.subs(fit) # Show the model
t |--> 0.92142857142840007*t + 0.64285714285636364
sage: plot(model.subs(fit),(t,0,5))+points(data,size=20,color='red') # Nice plot

When you have a huge number of points and you want just a polynomial fit, I found that it is (numerically) better to use the polyfit function from numpy:

sage: import numpy as np
sage: a,b=np.polyfit(x,y,1)
sage: a,b
(0.92142857142857137, 0.64285714285714401)
edit flag offensive delete link more

answered 2011-09-24 23:32:15 -0600

Dirk Danckaert gravatar image

I didn't find any reference to linear regression in the SAGE reference manual. That means you have to use Maxima directly. Fortunately that's not so difficult.

It's easier if you present the data as a list of pairs (x,y). Try this in a SAGE notebook cell:



You are presented a whole bunch of statistics about the regression. From there on I guess you can manage on your own. Good luck.

edit flag offensive delete link more

answered 2011-09-25 16:11:50 -0600

kcrisman gravatar image

I have a feeling that the answer to this ask.sagemath question may also be helpful. It mentions the built-in find_fit method.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2011-09-23 21:31:50 -0600

Seen: 1,953 times

Last updated: Sep 26 '11