Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find if a number is within a range in Java? Problems with Math.abs(num1-num2) <= inRange

Tags:

java

math

I've seen in another question that the solution to finding if your number is in a range was,

Math.abs(num1-num2) <= inRange

Where inRange is the number you are trying to figure out if it is in range between num2 and num1.

Where this formula breaks for me is when I insert these numbers.

Math.abs(25-(-25)) <= -5

I'm trying to find if -5 is in between -25 and 25. This equation is false even though the answer is true, -5 falls between -25 and 25.

Please clarify for me!

like image 281
KRB Avatar asked Nov 02 '11 06:11

KRB


People also ask

How do you check if a number falls within a range in Java?

ValueRange. of(minValue, maxValue); range. isValidIntValue(x); it returns true if minValue <= x <= MaxValue - i.e. within the range.

How do you find the range in Java?

Range = Max – Min. Coefficient of Range = (Max – Min) / (Max + Min)

What is abs () in Java?

The abs() method returns the absolute (positive) value of a number.

How do you find the range of two numbers in Java?

between() is a static method of the Range which is used to obtain an instance of Range with the specified minimum and maximum value. The specified minimum and maximum values are inclusive in nature.


1 Answers

For bonus points, there is a new Range class (used with helper class Ranges) introduced in Guava 10.x:

import com.google.common.collect.Range;
import com.google.common.collect.Ranges;

public class RangeTest {

    Range<Integer> range = Ranges.closed(-25, +25);

    public boolean rangeTest(Integer candidate) {
        return range.contains(candidate);
    }

}


public class TestMain {
    static RangeTest rangeTest = new RangeTest();

    public static void doTest(Integer candidate) {
        System.out.println(candidate + " in -25..+25: "
                + rangeTest.rangeTest(candidate));
    }

    public static void main(String[] args) {
        doTest(-26);
        doTest(-25);
        doTest(-24);
        doTest(-1);
        doTest(-0);
        doTest(+1);
        doTest(+24);
        doTest(+25);
        doTest(+26);
    }

}

Output:

-26 in -25..+25: false
-25 in -25..+25: true
-24 in -25..+25: true
-1 in -25..+25: true
0 in -25..+25: true
1 in -25..+25: true
24 in -25..+25: true
25 in -25..+25: true
26 in -25..+25: false

The Range class supports open and closed ranges, ranges from -INF to +INF, and all sorts of range-related operations like membership, intersection, and span.

like image 189
Steve J Avatar answered Nov 04 '22 16:11

Steve J