If you have studied any engineering career, you should have studied at some point numeric analysis and learned the least-squares method. Just remembering you, least-squares method aims to minimize the error of the given points when guessing the curve coefficients.

So, if you have some points and you know the order of the equation, this is what you need to know to get the coefficients.

I will write in this article how I used a PHP Artifical Intelligence library to solve any N-order linear equation.

The Machine Learning Library for PHP

I must say this PHP library is more than awesome, it implements many Artificial Intelligence algorithms, but for now, I will focus on least-squares.

You must have PHP 7 to use this library, also there is not an easy way to install it without the composer. The Github project website explains very well the installation process. So, I will skip it.

The Third Grade Equation Experiment

I selected the following equation as a test subject: f(x) = 2x^{3}−x^{2}+x−1. The following graph is the result of this equation.

Some of the points are:

x

f(x)

-4

-149

-3

-67

-2

-23

-1

-5

0

-1

1

1

2

13

3

47

4

115

Coding in PHP

Here it is the code I am using. It is quite simple.

include 'vendor/autoload.php'; use Phpml\Regression\LeastSquares;

Since the f(x) = Ax^{3} + Bx^{2} + Cx + D form is, the $sample array contains the values of x^{3}, x^{2} and x. The $target array cointains the values of f(x). Remember that the problem here is we do not know A, B, C and D; we only have some points and we know the order of the equation.

Please note that $targets array is having results with errors. I put these errors on purpose.