Forum Moderators: coopster

Message Too Old, No Replies

Function needed - line chart - Linear Interpolation - Missing Values

Function needed - line chart - Linear Interpolation - Missing Values

         

HappyJupiter

2:49 pm on Aug 14, 2010 (gmt 0)

10+ Year Member



Hello!

I am building a line graph from an array that is built from a db of user entered data.

What I need help with is adding any missing values. (Linear Interpolation)
Figuring out the value if there is only 1 value missing is simple (start value+end value/2), but if there is more than 1 value missing in a row it becomes more difficult.

1 missing value example:
$sample=array(1.3,2.1,,4.7);
how to figure it out: the missing value is this case is (2.1+4.7)/2 = 3.4

2 missing value example:
$sample=array(2.4,3.1,,,6.9);
how to figure it out: ?

I need a php function that accepts 3 vars and returns the calculated values for each of the missing values. (I guess it makes sense to return the calculated values in an array)

function buildMissingValues($startValue,$endValue,$numberOfMissingValues){
//brilliant code here
}

In the above "2 missing value" example I would like to:

$newValues=buildMissingValues(3.1,6.9,2);

and have an array returned with 2 values that complete the line chart points.

I'm not sure if I have explained this well enough.

I REALLY appreciate your help!

astupidname

12:22 am on Aug 15, 2010 (gmt 0)

10+ Year Member



Hi HappyJupiter and welcome to webmasterworld! The below will do what you want (note the round() function usage rounding the $n to 1 decimal place, you may or may not want this -tweak to your desire):

function buildMissingValues($startValue, $endValue, $numberOfMissingValues){ 
$step = ($endValue - $startValue) / ($numberOfMissingValues + 1);
$a = array();
for ($i = 1; $i <= $numberOfMissingValues; $i++) {
$n = $startValue + ($step * $i);
array_push($a, round($n, 1));
}
return $a;
}

$newValues = buildMissingValues(3.1, 6.9, 2);
print_r($newValues);

HappyJupiter

1:14 am on Aug 15, 2010 (gmt 0)

10+ Year Member



Great! I was sooo close :)

Thanks for saving me some brainpower today!