'Check if two numbers are close to each other

I want to check if two numbers are within a range of each other, by a given value.

boolean withinRange(double input1, double input2, double deviation){

//input1 will always be the biggest value
  if(input1 > input2){
    //do nothing
  } else if(input1 < input2) {
    double temp = input1;
    input1 = input2;
    input2 = temp;
  } else if(input1 == input2){
    return true;
  }

  if(input2 + deviation < input1 - deviation < input2){
    return true;
  } else {
    return false;
  }
}

So inputs like withinRange(2,3,2) should be true, but withinRange(1,4,2) should be false. I know the code is wrong, but I am not sure howto solve it. It is coded in Arduino, so very simular to C.

c


Solution 1:[1]

This is usually done like so, quite simply:

bool withinRange(double input1, double input2, double deviation)
{
  return fabs(input1 - input2) <= deviation;
}

Note that the C Boolean type is called bool. I edited to make the answer include the boundary, that is more intuitive so it might make it easier to verify.

Basically the absolute value of a subtraction is the distance between the two terms, so we compute that and compare it against the limit.

Solution 2:[2]

double out = num1 - num2;
if(out < 0) out *= -1;
if(out <= deviation)
    return true;
else return false;

This should work. You can also try to check which number is bigger and then swap them if needed.

Solution 3:[3]

You can just check if a number is in the range of the another number +/- range :

boolean withinRange(double input1, double input2, double deviation)
{
    return (input1 - deviation <= input2 && input2 <= input1 + deviation);
}

Solution 4:[4]

i will just say:

public bool checkInRange(float a, float b, double deviation)
{
    if (a < b)
    {
        a = a + b;
        b = a - b;
        a = a - b;
    }

    return ((a - b) <= deviation || a == b);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Tom's
Solution 4 Stupid Dev