Calculate if the value exceeds percentage <> numeric deadbands of the previous value.
The first function is for percentage. It detects if $value
is $deadband%
greater or less than $previous.
The second is for numeric difference. It detects if the difference between $value
and $previous
is greater than $deadband
.
function percentage_deadband($value,$previous,$deadband)
{
if($previous==0 || $value==0 || $previous == $value)
{
return false; //if previous or value is 0, we can't work. assume false.
}
$percentage = $value / $previous * 100;
if($percentage > 100){
return $percentage - $deadband > 100;//if percentage - deadband > 100, we know the deadband is exceeded
}
if($percentage < 100){
return 100 - $percentage > $deadband;//if 100 - percentage is greater than deadband, we know the deadband is exceeded
}
return false;
}
function numeric_deadband($value,$previous,$deadband)
{
if($previous==0 || $value==0 || $previous == $value)
{
return false;
}
if($previous > $value){
return $previous - $deadband >= $value;
}else{
return $value - $previous >= $deadband;
}
return false;
}
Testing the functions
$numeric_deadband = 3;
$numeric_set = [
0=>['value'=>77,'previous'=>80],//true
1=>['value'=>78,'previous'=>77],//false
2=>['value'=>81,'previous'=>78],//true
3=>['value'=>81,'previous'=>81]//false
];
echo '<strong>numeric set:</strong><br/>';
foreach($numeric_set as $row)
{
var_dump(numeric_deadband($row['value'],$row['previous'],$numeric_deadband));
echo '<br/>';
}
echo '<br/>';
$percentage_deadband = 10;
$percentage_set = [
0=>['value'=>27,'previous'=>39],//true
1=>['value'=>39,'previous'=>40],//false
2=>['value'=>41,'previous'=>28],//true
3=>['value'=>28,'previous'=>31]//false
];
echo '<strong>percentage set:</strong><br/>';
foreach($percentage_set as $row)
{
var_dump(percentage_deadband($row['value'],$row['previous'],$percentage_deadband));
echo '<br/>';
}
They seem to work correctly with my small set of test data, but I am not so great with math. I'd love a second opinion.
$n
represents$value
as a percentage of$previous
. You could also remove the lastif
statement from the first function - you're returning false either way. You also might want to be more descriptive with your variable named$n
- maybe try$percentChange
\$\endgroup\$