Newer
Older
Ruby / monte.rb.txt
@SASAKI Mirai SASAKI Mirai on 16 Oct 2021 820 bytes 2021-10-16 10:27:38
puts "Monte Carlo method.csvを作成します"
puts "pi.csvを作成します"

file = File.open("Monte Carlo method.csv", "w")
file2 = File.open("pi.csv", "w")

puts "乱数を10000行分生成します"
count = 0
count_in = 0

10000.times do
  count += 1
  x = Random.rand        # 発生させた乱数をxに代入
  y = Random.rand        # 発生させた乱数をyに代入
  puts "#{x},#{y}"       # x,yを画面に表示
  file.puts "#{x},#{y}"  # x,yをファイルに書き込み
  if x**2 + y**2 <= 1
    count_in += 1
    pai = 4.0 * count_in / count
    file2.puts  "#{count_in}, #{pai}"
  end
  puts count
  puts count_in
  puts pai
end

puts "乱数をMonte Carlo method.csvに保存しました"
puts "paiの近似値をpi.csvに保存しました"

file.close
file2.close