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.
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.
I selected the following equation as a test subject: f(x) = 2x3−x2+x−1. The following graph is the result of this equation.
Some of the points are:
Here it is the code I am using. It is quite simple.
$samples = [[-64,16,-4], [-27,9,-3], [-8,4,-2], [-1,1,-1], [0,0,0], [1,1,1], [8,4,2], [27,9,3], [64,16,4]];
$targets = [-148, -65, -24, -5, -2, 1, 14, 45, 117];
$regression = new LeastSquares();
Since the f(x) = Ax3 + Bx2 + Cx + D form is, the $sample array contains the values of x3, x2 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.
I got the following output:
 => 2.013468013468
 => -0.88744588744589
 => 0.7744107744108
Which it means g(x) = 2.013468013468 x3 - 0.88744588744589 x2 + 0.7744107744108 x - 1.5281385281385.
Let's evaluate against 5, f(5) = 229 and g(5) = 231.84126984127 which it is pretty close. Look the graph f(x) in blue, g(x) in red.
Good luck!blog comments powered by Disqus
Most Read Posts in Technology
Read about IT, Migration, Business, Money, Marketing and other subjects.
Some subjects: FusionPBX, FreeSWITCH, Linux, Security, Canada, Cryptocurrency, Trading.