Reputation: 5175
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!
Upvotes: 9
Views: 69836
Reputation: 551
kotlin has .. operator
if (center.x in 0..MaxX) {
//Do stuff
}
if (center.y !in 0..MaxY) {
//Do stuff
}
Upvotes: 0
Reputation: 1
Old question, however the Math.abs method can be clearer depending what you're working on, and is still worth showing:
int x = 5;
int bounds = 25;
if(Math.abs(x) <= bounds) {
//run if x is anywhere between -25 and 25
}
Upvotes: 0
Reputation: 2674
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.
Upvotes: 8
Reputation: 1977
Below expression will check x
is between a
and b
:
Math.abs(x - a) + Math.abs(b - x) == Math.abs(b - a)
Upvotes: 2
Reputation: 22555
Just do:
bool isInRange = Math.min(num1,num2) <= inRange
&& Math.max(num1,num2) >= inRange;
Your current approach just checks number ranges. in fact smallest and largest number distance.
Upvotes: 7
Reputation: 1500665
I don't see any reason to use Math.abs
at all. I'd use:
if (lowerBound <= value && value < upperBound)
or
if (lowerBound <= value && value <= upperBound)
if you want the upper bound to be inclusive too.
Indeed, the Math.abs()
approach seems entirely broken - I strongly suspect that you misunderstood the question where it was posed as a solution.
Upvotes: 29