Linear Fitting – JAVA / Android [Code/Program]

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: x_i and y_i .
Then the fitted function can be calculated by minimizing:
where, Y_i are the fitted points.
Skipping all the math, we get the following formulae for m and c:
m= \frac{n\Sigma x_iy_i-\Sigma x_i \Sigma y_i}{n\Sigma x_i^2-(\Sigma x_i)^2}
c= \frac{\Sigma x_i^2 \Sigma y_i -\Sigma x_i \Sigma x_iy_i}{n\Sigma x_i^2-(\Sigma x_i)^2}

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++){


Linear Fit code being used in an app

So that’s it.
You now have the value of ‘m'(slope) and ‘c'(intercept) and thus the linear fit:
y=mx + c

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

PhD researcher at Friedrich-Schiller University Jena, Germany. I'm a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT and Machine Learning related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.
[wpedon id="7041" align="center"]

Leave a Reply

Your email address will not be published. Required fields are marked *