in reply to Bitshift limits
Just change ">>= 1" to "/= 2" plus similar changes to get:
and you are good up to about 52 bits (instead of 32), probably quite a bit farther (depends exactly how the round-off enters into the calculations). I didn't get even a one-bit error until I tried that on 36028797018963967 (which returned twice of one more than that number, instead of just one more than that number).$tmp = @ARGV[0]; $i = 0; while( 1 <= $tmp ) { $tmp /= 2; $i += 1; } print 2 ** $i;
I'd do this more like:
which exhibits the same problem but only because you can't represent 36028797018963967 exactly as a floating point number.sub nextpow2 { my $s= shift(@_); my $p= 1; $p *= 2 while $p <= $s; return $p; }
So this works for quite high powers of two provided your input isn't just under a large power of two.
- tye (don't fear the floating point)
|
|---|