Feb 11, 2014 at 7:16pm UTC
Hello.
I want to find a way to find the log_2 of a number that is supposedly a power of 2 using bitwise shift to improve the performance
Last edited on Feb 11, 2014 at 7:17pm UTC
Feb 11, 2014 at 9:35pm UTC
Remember that the
logn of any value is equivalent to the number of times that value can be divided by
n before it becomes 1. Or equivalently, how many times can we multiply n by itself before we get value.
So
log2 of 14 is:
1 2 3 4 5
14 / 2 <-- 1
7 / 2 <-- 2
3 / 2 <-- 3
1
= 3 (~3.8)
With bitwise shift, this is equivalent to right bitshift (divides by (2 ^ value specified))
1 2 3 4 5 6
log2 of 14 is:
[1110 = 2 ^ 3 + 2 ^ 2 + 2 ^ 1 + 2 ^ 0] 14 >> 1 // means 14 / (2 ^ 1) <-- 1
[111 = 2 ^ 2 + 2 ^ 1 + 2 ^ 0] 7 >> 1 // means 7 / (2 ^ 1) <-- 2
[11 = 2 ^ 1 + 2 ^ 0] 3 >> 1 // means 3 / (2 ^ 1) <-- 3
[1 = 2 ^ 0]
= 3
Last edited on Feb 11, 2014 at 9:40pm UTC
Feb 12, 2014 at 2:08am UTC
How can I turn 16 to zero?
for example I have numbers from 0 to 100 and four 25-numbers-wide buckets
e.g I want 16 to fall in the range 0 to 25
Feb 12, 2014 at 2:12am UTC
What do you mean 16 to fall in the range 0-25? You want to place 16 inside one of the buckets?
Feb 12, 2014 at 2:43am UTC
Are you doing a bucket sort now?
Feb 12, 2014 at 2:46am UTC
Not now, but I want to
and I should use the shift operator, since it is faster than division
Last edited on Feb 12, 2014 at 2:47am UTC
Feb 12, 2014 at 11:25pm UTC
You should not assume you can do a better job optimizing your code than your compiler can. (Not without first profiling it.)