Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
これだと偏る
#! /usr/bin/env ruby
require 'pp'
def shuffle(array)
i = array.length
while 0 < i
i = i - 1
j = (Random.rand * i).to_i
array[i], array[j] = array[j], array[i]
end
array
end
N = 10
M = 10_000
sum_array = Array.new(N, 0)
M.times do
ret = shuffle((1..N).to_a)
sum_array = sum_array.zip(ret).map { |x,y| x+y}
end
avg = ((1 + N) * N / 2).to_f / N
sum_array.map! {|n| n.to_f / M / avg}
pp sum_array
__END__
[1.0824181818181817,
1.0727454545454547,
1.0495818181818182,
1.0350727272727271,
1.0113454545454545,
0.9922727272727272,
0.9672727272727273,
0.9484727272727272,
0.9301636363636363,
0.9106545454545455]
@hanabokuro

This comment has been minimized.

Copy link
Owner Author

commented Jul 26, 2014

j = (Random.rand * (i + 1)).to_i
であるべきなのかな

@hanabokuro

This comment has been minimized.

Copy link
Owner Author

commented Jul 26, 2014

#! /usr/bin/env ruby

require 'pp'

def shuffle(array)
  i = array.length
  while 1 < i
    i = i - 1
    j = (Random.rand * (i+1)).to_i
    array[i], array[j] = array[j], array[i]
  end

  array
end

N = 10
M = 10_000

sum_array = Array.new(N, 0)
M.times do
  ret = shuffle((1..N).to_a)
  sum_array = sum_array.zip(ret).map { |x,y| x+y}
end

avg = ((1 + N) * N / 2).to_f / N
sum_array.map! {|n| n.to_f / M / avg}
pp sum_array

__END__

[0.9967636363636363,
 0.9968,
 1.0102363636363636,
 0.9960181818181819,
 0.9953454545454545,
 1.0029272727272727,
 1.0000909090909091,
 0.9993090909090909,
 1.0014727272727273,
 1.0010363636363637]

while loop も一回少なくできる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.