crossRT
crossRT

Reputation: 686

PHP calculate trend line like excel TREND function

My math is very week and now still figuring how to achieve this with PHP. I was using excel TREND() function. Let's say I have 2 lists of known values

| known_x_values | known_y_values | |----------------|----------------| | 323 | 0.038 | | 373 | 0.046 | | 423 | 0.053 | | 473 | 0.062 | | 523 | 0.071 | | 573 | 0.080 |

And now I need to know the value y when the x = 428. By using excel TREND() function, I get 0.055 as the value y.

Anyone can show me how PHP handle this kind of math questions?
Any help would be appreciated. Thank you.

Upvotes: 2

Views: 5288

Answers (1)

user3942918
user3942918

Reputation: 26405

Excel's TREND() uses the least squares method.

Math is hard, so I'd use a library to do the heavy lifting. In this case php-ai/php-ml.

Example:

use Phpml\Regression\LeastSquares;

$x = [[323], [373], [423], [473], [523], [573]];
$y = [.038, .046, .053, .062, .071, .080];

$regression = new LeastSquares();
$regression->train($x, $y);
echo $regression->predict([428]);

Outputs:

0.054973333333333235

Output may vary slightly depending on your precision setting.


You can of course round() or number_format() that result as you wish, e.g.:

echo number_format($regression->predict([428]), 3);

gives:

0.055

Upvotes: 8

Related Questions