Fitting functions to your data
If we want to get serious about fitting functions to our data, we can turn to gnuplot's sophisticated fit command.
Getting ready
You need the same datafile used in the previous recipe, rs.dat
. The following figure shows the same noisy sine wave, but this time the overlaid curve seems to be perfectly smooth:
How to do it…
The following script will produce the previous figure:
f(x) = a*sin(b*x)
fit f(x) 'rs.dat' via a, b
plot 'rs.dat' with lines lw 0.5 notitle, f(x) lw 4 title "Fit by gnuplot"
How it works…
gnuplot's fit
command takes a function defined by the user containing several parameters and attempts to find the set of values for these parameters that result in the best fit of the resulting function to the data specified. Best fit is in a nonlinear least-squares sense that is thoroughly discussed in the official gnuplot manual. After entering the fit
command, gnuplot will iterate, displaying intermediate results on the console, until it finds an acceptable fit...