chriss
chriss

Reputation: 4449

gnuplot fit line to two points

Consider the data file with two columns and two rows:

  3869.    1602.  
  3882.    9913.

I'd like to fit a line using gnuplot

gnuplot> f(x) = a * x + b
gnuplot> fit f(x) './data.txt' u 1:2 via a, b

Iteration 0
WSSR        : 3.43474e+07       delta(WSSR)/WSSR   : 0
delta(WSSR) : 0                 limit for stopping : 1e-05
lambda   : 2740.4

initial set of free parameter values

a               = 1.7524
b               = -1026.99
/

Iteration 1
WSSR        : 3.43474e+07       delta(WSSR)/WSSR   : -1.49847e-12
delta(WSSR) : -5.14686e-05      limit for stopping : 1e-05
lambda   : 274.04

resultant parameter values 

a               = 1.7524
b               = -1026.99

After 1 iterations the fit converged.
final sum of squares of residuals : 3.43474e+07
rel. change during last iteration : -1.49847e-12


Exactly as many data points as there are parameters.
In this degenerate case, all errors are zero by definition.

Final set of parameters 
======================= 

a               = 1.7524         
b               = -1026.99       
gnuplot>

which gives wrong values for fit parameters. Why is this happening? My gnuplot version is Version 4.4 patchlevel 0.

Upvotes: 1

Views: 2215

Answers (2)

Woltan
Woltan

Reputation: 14023

Gnuplot uses a non-linear method to determine the parameters of your function f with respect to a certain error value: limit for stopping : 1e-05.

If you change that error value your function will be exactly fit. The error value can be specified with the FIT_LIMIT variable like so:

FIT_LIMIT = 1e-8

With this setting your points will be exactly matched after 12 iterations. (At least on my machine^^)

Upvotes: 1

William Menz
William Menz

Reputation: 131

It looks to me that the curve-fitting function is struggling to find the true parameters. This could be associated with the magnitude of your data points and/or trying to fit a line with two parameters to only two data points.

In any case, doing the calculation of a and b in Excel or equivalent yields:

a= 577.769
b = -2233787

If you give gnuplot a good guess at what they should be, e.g. a=500 and b=-2233700 and repeat the procedure, it should successfully find the correct solution:

Final set of parameters 
======================= 

a               = 577.769        
b               = -2.23379e+06   

Of course, if you're fitting two points to a two-parameter straight line, it's much easier to calculate the values of a and b by hand:

a = (9113-1602) / (3882-3869)
b = 1602 - a * 3869

Upvotes: 1

Related Questions