Skip to content

Instantly share code, notes, and snippets.

@pocari
Last active August 24, 2019 14:28
Show Gist options
  • Save pocari/357797f1f216c015aac8e0f5905004b7 to your computer and use it in GitHub Desktop.
Save pocari/357797f1f216c015aac8e0f5905004b7 to your computer and use it in GitHub Desktop.
rubyで即値になる数値とobjectになる数値の境界を探す
def immediate_value?(number)
(number.object_id >> 1) == number
end
def bin_search(min, max)
# p [:try, min, max]
if (max - min) <= 1
puts "stop"
puts "min: #{min}, bit_length: #{min.bit_length} check: #{immediate_value?(min)}"
puts "max: #{max}, bit_length: #{max.bit_length} check: #{immediate_value?(max)}"
else
center = (max + min) / 2
if immediate_value?(center)
bin_search(center, max)
else
bin_search(min, center)
end
end
end
bin_search(1, 2 ** 64 - 1)
@pocari
Copy link
Author

pocari commented Aug 24, 2019

https://github.com/ruby/ruby/blob/1bd60c66d385142d08f678f8a9563c311cfc3fe8/include/ruby/ruby.h#L257
を元にチェック

show_fix_num_max.c

#include <stdio.h>
#include <limits.h>

int main(void) {
  printf("LONG_MAX >> 1 = %ld\n", LONG_MAX >> 1);

  return 0;
}
% gcc show_fix_num_max.c
% ./a.out
LONG_MAX >> 1 = 4611686018427387903
% ruby fixnum_immediate_value_boundary.rb
stop
min: 4611686018427387903, bit_length: 62 check: true
max: 4611686018427387904, bit_length: 63 check: false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment