Ruby: shift right operator (>>) does not work correctly

It seems to be a bug with >> operator:

4653896912 >> 13 should be 43814 like it is in java or php, but not
568102.

Tested with ruby 1.8.2 in windows xp and freebsd.

any related issues to this subject?

Best regards,
Vitalie

Vitalie Lazu wrote:

It seems to be a bug with >> operator:

4653896912 >> 13 should be 43814 like it is in java or php, but not
568102.

Tested with ruby 1.8.2 in windows xp and freebsd.

any related issues to this subject?

Best regards,
Vitalie

Math.log(4653896912) / Math.log(2)
=> 32.1157921080915

There you have it, the number 4653896912 cannot be represented in 32
bits (it needs 33 bits, 34 if you add a sign bit). Java is truncating
the value:

(4653896912 & 0xffffffff)
=> 358929616
358929616 >> 13
=> 43814

– Jim W.

Thanks all

Vitalie Lazu wrote:

Vitalie

Why should anything be like java and php?

$ ruby -e ‘puts 4653896912 >> 13’
568102
$ python -c ‘print 4653896912 >> 13’
568102
$ ruby -e ‘puts 4653896912.0 / (213)’
568102.650390625
$ python -c 'print 4653896912.0 / (2
13)’
568102.650391
$ echo ‘4653896912.0 / (2^13)’ | bc
568102
$ cat t.c
main(){
printf("%d\n", 4653896912 >> 13);
}
$ tcc -run t.c
568102

Maybe there is a bignum problem in java/php?

Perl (v5.8.7), on the other hand, seems to be in its own world…

$ perl -e ‘printf “%s\n”, 4653896912 >> 13’
524287

14.times do
irb#1(main):006:1* |i|
irb#1(main):007:1* puts “#{x} >> #{i} = #{x >> i }”
irb#1(main):008:1> end
4653896912 >> 0 = 4653896912 looks good
4653896912 >> 1 = 2326948456 looks great
4653896912 >> 2 = 1163474228 looks fine
4653896912 >> 3 = 581737114 looks alright
4653896912 >> 4 = 290868557 looks pretty
4653896912 >> 5 = 145434278 looks ok
4653896912 >> 6 = 72717139 looks nice
4653896912 >> 7 = 36358569 looks correct (that is an ugly one)
4653896912 >> 8 = 18179284 looks as it should
4653896912 >> 9 = 9089642 looks half of the above
4653896912 >> 10 = 4544821 looks as expected
4653896912 >> 11 = 2272410 looks superb
4653896912 >> 12 = 1136205 looks hey I am not a native speaker
4653896912 >> 13 = 568102 looks good for ruby and bad for some
other
programming toys
=> 14

Cheers
Robert


Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.

  • Albert Einstein

Joel VanderWerf schrieb:

Maybe there is a bignum problem in java/php?

Perl (v5.8.7), on the other hand, seems to be in its own world…

$ perl -e ‘printf “%s\n”, 4653896912 >> 13’
524287

(flori@combinator:~ 0)$ perl -e 'use bignum; printf “%s\n”, 4653896912

13’
568102