Salman Arshad
Salman Arshad

Reputation: 272236

How to check if array values are almost same

I have an array that contains seven numbers:

array(159.60, 159.60, 159.60, 159.60, 159.60, 199.50, 199.50);
array(395.68, 395.68, 395.68, 395.68, 395.68, 395.68, 395.68);
array(531.18, 531.18, 531.18, 531.19, 531.18, 531.18, 531.18);

I need to check if all values are same, with one twist: sometimes the values differ slightly because of rounding off errors (see 4th value in 3rd array). I want them considered same.

What would be the best way to check if all array values are same within a tolerance value, say 0.1.

Upvotes: 1

Views: 153

Answers (2)

Sougata Bose
Sougata Bose

Reputation: 31749

For each array we can find the max & min value and check if it is greater than 0 or not as @zerkms suggested.

$tests = array(
    array(159.60, 159.60, 159.60, 159.60, 159.60, 199.50, 199.50), 
    array(395.68, 395.68, 395.68, 395.68, 395.68, 395.68, 395.68), 
    array(531.18, 531.18, 531.18, 531.19, 531.18, 531.18, 531.18)
);
foreach ($tests as $i => $test) {
    $result = abs(max($test) - min($test)) <= 0.1;
    var_dump($result);
}

Output

bool(false)
bool(true)
bool(true)

CODE

Upvotes: 2

Liam Wiltshire
Liam Wiltshire

Reputation: 1264

You could write a pretty simple loop to check this:

function withinTolerance($array,$tolerance){
    $initialValue = $array[0]; //Set the initial value
    foreach ($array as $num){
        //Loop the array, and if the value is outside the tolerance, return false.
        if ($num < $initialValue - $tolerance || $num > $initialValue + $tolerance) return false;
    }

    return true;
}

Upvotes: -1

Related Questions