In this post I would be explaining the code to find the best linear fit for a given set of data points.
Or in other words, the equation of a line that best fits a given set of data.
The equation of a line is given by:
where ‘m’ is the slope and ‘c’ is the intercept.
So we will need to determine these constants in the above equation.
We will be using the Least Squares Method to achieve this.
Let’s say you have n data points: and .
Then the fitted function can be calculated by minimizing:
where, are the fitted points.
Skipping all the math, we get the following formulae for and :
You can refer to this link for a detailed proof.
The following JAVA Code for linear fitting works for android devices too.
Let’s say you have declared two arrayLists to store the x-axis and y-axis values.
public static ArrayList<String> x_axis=new ArrayList<String>(); public static ArrayList<String> y_axis=new ArrayList<String>();
int n=x_axis.size(); for(int i=0;i<n;i++){ xsum=Double.parseDouble(x_axis.get(i))+xsum; ysum=Double.parseDouble(y_axis.get(i))+ysum; xysum=Double.parseDouble(x_axis.get(i))*Double.parseDouble(y_axis.get(i))+xysum; x2sum=Double.parseDouble(x_axis.get(i))*Double.parseDouble(x_axis.get(i))+x2sum; } m=(n*xysum-xsum*ysum)/(n*x2sum-xsum*xsum); c=(x2sum*ysum-xsum*xysum)/(x2sum*n-xsum*xsum);
So that’s it.
You now have the value of ‘m'(slope) and ‘c'(intercept) and thus the linear fit:
To make your code even cleaner, you could wrap all the above code into a method/function and then pass the ‘x’ and ‘y’ datapoints as arraylists and get back the values of ‘m’ and ‘c’.
The reason I didn’t do it is because Java sucks and doesn’t even support multiple return variables.
So I would have had to return the values in an array, and it felt unnecessary.
You can refer to the following links for more info:
Linear Fitting – Lab Write-Up
Linear Fitting – C++ Program
Linear Fitting – Scilab Code
Curve Fit Tools – Android App (using the above code)
Curve Fit Tools – Documentation
Curve Fit Tools – Play Store
Curve Fit Tools – GitHub Repository
Curve Fitters – Scilab Toolbox
I’m a physicist specializing in computational material science with a PhD in Physics from Friedrich-Schiller University Jena, Germany. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.