Determining if an interval contains at least one integer without math.h
For a class project, I need to split multiple audio clips into smaller sections for which we are given the minimum length and maximum length, to find out if this is possible, I do the following:
a = length/max
b = length/min
mathematically I figured out that [a, b] contains at least one integer if βbβ >= βaβ
, but I cannot use math.h for floor () and ceil (). Since a and b are always positive, I can use type casting for floor (), but I don't understand how to do ceil (). I was thinking about using ((int) x) +1, but those are round integers that would break the formula.
I would like to either do a ceil (), which would solve my problem, or another way to check if an interval contains at least one integer.
source to share
You don't need math.h
to do the floor. Take a look at the following code:
int length=5,min=2,max=3; // only an example of inputs.
int a = length/max;
int b = length/min;
if(a!=b){
//there is at least one integer in the interval.
}else{
if(length % min==0 || length % max==0 ){
//there is at least one integer in the interval.
}else{
//there is no integer in the interval.
}
}
The result for the above example would be that there is an integer in the range.
You can also ceil without using math.h
like this:
int a;
if(length % max == 0){
a = length / max;
}else{
a = (length / max) + 1;
}
source to share
There is a common programming trick that will come to hand if you ever find Apple Basic programming or any other language that supports floating point math.
You can "round" a number by adding, then truncating, as follows:
x = some floating value
rounded_x = int(x + roundoff_amount)
Where roundoff_amount
is the difference between the bottom fraction and rounding up, and 1.
So to round to 0.5, your round_off would be 1 -.5 = .5 and you would int(x + .5)
. If x is .5 or .51 then the result will be 1.0 or 1.01 and int()
will be 1. Obviously if x is higher then you will still round to 1 until x is 1.5 when rounding results in 2. To round up, starting at 0.6, your rounding sum is 1 -.6 = .4, and you do int(x + .4)
, etc.
You can do this to get the behavior ceil
. Set roundoff_amount to 0.99999 ... and complete the round. You can choose your own value to provide a "sibling" window, since floats have some inaccuracy that can prevent them from getting a perfectly integer value after adding fractions.
source to share
If I understood that you are asking the question correctly, I think you can do ceil (a) in this case and then check if the result is less. So, for example, for the interval [1.3, 3.5], ceil (1.3) will return 2, which fits into this interval.
UPD You can also do (b - a). If it is> 1, then, of course, at least one integer between them.
source to share