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.

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>();

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.

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.