This post is an extension of his previous article, “Fitting a plane to many points in 3D”, and together they provide an incredible explanation of how to efficiently compute a best-fit plane for points in three-dimensional space.
The culmination of Emil’s work is a 81-line program (which appears to be written in Rust, though I’m not certain) which can take a set of 3-vectors (X, Y, Z) as input and return the centroid point along with the normal associated with a best-fit plane for those points. His code can be found at the end of the first post linked at the beginning of this article.
Below, I have written a Python version of the same algorithm. Specifically, my implementation uses the Numba library to achieve just-in-time compilation for maximum computational efficiency. This allows the code to be used within Python programs, while achieving an execution speed much closer to that of C/C++. The compilation is handled entirely by Numba and controlled with a single function decorator. To disable this Numba functionality for compatibility reasons, simply comment-out the @jit(nopython=True) line at the beginning of the function.
Differences in my Implementation:
The results are extended to compute A, B, C, and D coefficients representing the plane
Normalization is performed to ensure that (A, B, C) is a vector of length 1.0
NOTE: The coefficients returned follow the convention Ax + By + Cz + D = 0, with all variables on the same side of the equation.