1

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.

2
  • 2
    Find the min/max elements and subtract them. Commented Dec 8, 2015 at 10:36
  • 1
    @zerkms, you can actually write that as answer. Commented Dec 8, 2015 at 10:37

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

7 Comments

That's funny you decided to remove credits to me :-D (not that it was important to me - but I find it curious that you initially put them then removed)
@zerkms I was updating the answers with some descriptions. You can see it now. Hope you get it.. :)
Not 0, but should be like: (max($ar) - min($ar)) <= tolerance
What are you doing...@Sougata? Not >0, but <=tolerance
I'm off. I'm not even sure why something that takes 30 seconds to implement needs a 20 minutes discussion :-D
|
-1

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;
}

7 Comments

This solution is broken: the 0-th element does not have any special properties so that you could rely on it.
bad answer. Say, tolerance=1, array= {5,6,4,5,5,5,5}. Your function returns true...it should, false.
@SalmanA well, why not with element with index 1 or 42? What is the maths behind this magic: $num < $initialValue - $tolerance?
@SalmanA are you sure you have come through all the comments to this answer?
@SalmanA not sure what "incorrect" means. The second comment perfectly demonstrates the implementation flaw.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.