Introduction
Method to derive a best fit a plane through number (≥ 3) XYZ data points, where the summed square errors of the data points in relation to the fit-plane in Z-direction is minimal.
Equation of a plane
$z\left(x,y\right)=A\cdot \ x+B\cdot \ y+C$
Data points
$\left[\begin{matrix}x_1&y_1&z_1\\x_2&y_2&z_2\\x_3&y_3&z_3\\&\vdots&\\x_n&y_n&z_n\\\end{matrix}\right]$
Coefficients of plane equation
$\left[\begin{matrix}A\\B\\C\\\end{matrix}\right]=\left[\begin{matrix}\sum_{i=1}^{n}x_i^2&\sum_{i=1}^{n}{x_iy_i}&\sum_{i=1}^{n}x_i\\\sum_{i=1}^{n}{x_iy_i}&\sum_{i=1}^{n}y_i^2&\sum_{i=1}^{n}y_i\\\sum_{i=1}^{n}x_i&\sum_{i=1}^{n}y_i&\sum_{i=1}^{n}1\\\end{matrix}\right]^{-1}\cdot\left[\begin{matrix}\sum_{i=1}^{n}{x_iz_i}\\\sum_{i=1}^{n}{y_iz_i}\\\sum_{i=1}^{n}z_i\\\end{matrix}\right]$
Tip / Tilt angles
$Rx=\arctan{\left[\frac{d}{dy}z\left(x,y\right)\right]}=\arctan{\left[B\right]}$
$Ry=\arctan{\left[-\frac{d}{dx}z\left(x,y\right)\right]}=\arctan{\left[-A\right]}$
Fit quality – Coefficient of determination = R2
$R^2=1-\frac{\sum_{i=1}^{i=n}\left(z_i-z\left(x_i,y_i\right)\right)^2}{\sum_{i=1}^{i=n}\left(z_i-\frac{1}{n}\sum_{i=1}^{n}z_i\right)^2}$
A value of $R^2$ which is close to 1 indicates a good fit quality.