Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closest integer value to 20

Tags:

java

division

If I have a number greater than 20 but that can be divided evenly by 2 without any remainder, I want to determine what number gets me closest to 20. For example:

For 2048, dividing by 2 enough times would get me to 16 which is the closest I can get to 20. If the number is 800, the closest is 25.

I can write a loop and just keep dividing and comparing the range and pick the value that is closest. Is there maybe a simpler way, possibly through shifting bits?

EDIT: When I say it evenly divides by 2, I mean it divides all the way down to 2 as well. A number of 70 would only divide down to 35 evenly. A number like 2048 or 1024 will divide evenly all the way to 2.

Sample numbers: 2048, 1920, 1600, 1536, 1080..640, 352, 320, 176. These are typical image sizes from cameras.

like image 289
Johann Avatar asked Jan 22 '13 10:01

Johann


People also ask

What is the closest integer?

Rounding to the nearest integer is really rounding to the nearest units place. Sometimes, you will be asked to round to the nearest hundreds, or to the nearest hundredths — to some decimal place other than the units place. The rule is just a more generalized version of the previous rounding rule.

What is the closest value to 0?

If you mean integer then 1 (or -1) is the closest integer to zero. I expect however that you mean rational number or real number. In this case there is no number closest to zero. You can see this by letting be any real or rational number that is not equal to zero.

Is 0 an integer number?

As a whole number that can be written without a remainder, 0 classifies as an integer.

What does it mean to round up to the nearest integer?

Rounding up, sometimes referred to as "taking the ceiling" of a number means rounding up towards the nearest integer. For example, when rounding to the ones place, any non-integer value will be rounded up to the next highest integer, as shown below: 5.01. ⇒ 6.


1 Answers

If your input number is x, I think you want x/2^[(log x/14)/log 2], assuming you want your target number to be in the interval [14,27].

In java code, Math's log function will come in handy (although base-2 logarithm would be even better), and you also need an integer cast (or somehow find the largest integer smaller than the expression in []).

What this does: Let x be your input and y be the number you want to find. Then, x=y*2^n for yet unknown n, while y is around 20 (see above). Obviously, n is the base-2 logarithm of x/y. Now, if you pick the smallest possible y, call it y', the integer part of the base-2 logarithm of x/y' is still the n we are looking for, unless x/y' differs from x/y by a factor of more than 2, which by assumption of repeated division by 2 it cannot. Thus, we have n and hence y=x/2^n.

like image 84
arne.b Avatar answered Sep 24 '22 07:09

arne.b