Drkcore

12 09 2009 OCaml Tweet

arcsinのテーラー展開でπをもとめる(ocamlで)

let rec power m = function
    0 -> 1
  | n -> m * power m (n-1)
;;

let rec factorial = function
    0 -> 1
  | n -> n * factorial (n-1)
;;

let rec calc_pi = function
    0 -> 3.0
  | n -> (float_of_int (3 * factorial(2*n))) /.
 (float_of_int ((power 2 (4*n)) * (power (factorial n) 2) * (2*n+1))) +. calc_pi (n-1)
;;

これだとcalc_pi 6ぐらいでneg_infinityになってしまう。あと型で結構つまづく。

普通に求めるヤツ

let mc () =
let x = Random.float 1.0 in
let y = Random.float 1.0 in
if sqrt ((x ** 2.0) +. (y ** 2.0)) <= 1.0 then 1
else 0
;;

let rec count n res = match n with
  0 -> res
| _ -> count (n-1) (res + mc())
;;

let calc_pi n =
  let res = count n 0 in
  (float_of_int res)*.4.0 /. (float_of_int n)
;;

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021