Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define trends according to some values?

Tags:

php

math

I am trying to to mark some trends, so I have 1 as the lowest and 5 as the biggest value.

So for example,

I may have the following case:

5,4,5,5   (UP)
3,4,      (UP)
4,3,3     (DOWN)
4,4,4,4,  (FLAT - this is OK for all same numbers)

I am planning to have unlimited number of ordered values as input, an as an output I will just show an (UP), (DOWN), or (FLAT) image.

Any ideas on how I can achieve this?

Sorry if I am not descriptive enough.

Thank you all for you time.

like image 431
Adnan Avatar asked Dec 06 '25 03:12

Adnan


1 Answers

Use least square fit to calculate the "slope" of the values.

function leastSquareFit(array $values) {
    $x_sum = array_sum(array_keys($values));
    $y_sum = array_sum($values);
    $meanX = $x_sum / count($values);
    $meanY = $y_sum / count($values);
    // calculate sums
    $mBase = $mDivisor = 0.0;
    foreach($values as $i => $value) {
        $mBase += ($i - $meanX) * ($value - $meanY);
        $mDivisor += ($i - $meanX) * ($i - $meanX);
    }

    // calculate slope
    $slope = $mBase / $mDivisor;
    return $slope;
}   //  function leastSquareFit()

$trend = leastSquareFit(array(5,4,5,5));

(Untested)

If the slope is positive, the trend is upwards; if negative, it's downwards. Use your own judgement to decide what margin (positive or negative) is considered flat.

like image 190
Mark Baker Avatar answered Dec 08 '25 17:12

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!