From: Rick DeNatale Date: 2006-08-10T05:29:28+09:00 Subject: Re: nextPowerOf2(n) On 8/7/06, Simon Kr�ger wrote: > Rick DeNatale wrote: > > On 8/7/06, Simon Kr�ger wrote: > >> Rick DeNatale wrote: > > > >> > My original intention was to benchmark the various suggestions, but > >> > since you can get the wrong answers with arbitrarily fast code, I > >> > don't think that it matters much. > >> > >> Hmm, what about: > >> > >> def next_power_of_2(n) > >> throw 'eeek' if n < 0 > >> return 1 if n < 2 > >> 1 << (n-1).to_s(2).size > >> end > >> > >> ? > > > > Ahh, but the following is both quicker and more economical of source code > > > > def next_power_of_2(n) > > end > > > > If you don't care about a correct answer, then nil is as good as any. > > would you dare to explain? > > def next_power_of_2(n) > throw 'eeek' if n < 0 > return 1 if n < 2 > 1 << (n-1).to_s(2).size > end > > puts next_power_of_2(0) #=> 1 > puts next_power_of_2(1) #=> 1 > puts next_power_of_2(2) #=> 2 > puts next_power_of_2(3) #=> 4 > puts next_power_of_2(4) #=> 4 > puts next_power_of_2(5) #=> 8 > puts next_power_of_2(255) #=> 256 > puts next_power_of_2(256) #=> 256 > puts next_power_of_2(257) #=> 512 > puts next_power_of_2(536870911) #=> 536870912 > puts next_power_of_2(536870912) #=> 536870912 > puts next_power_of_2(536870913) #=> 1073741824 > > seems to be correct for a lot more cases than nil(?) You had to go a bit further back in the thread. All of the versions which relied on float math functions fell apart for differing increasing values of n as the floating point math starts to diverge from 'pure' math. I never said that it wasn't possible to write a method which produced accurate answers, only that those float based ones don't and that there was no sense in benchmarking implementations which produce bogus results against those which do. -- Rick DeNatale