読者です 読者をやめる 読者になる 読者になる

PI

prolog

Prologで作る数学の世界―Prologそして集合‐位相‐群の第3章の問題。arctanを定義してπの近似値を求めろ。最初に書いた効率の悪いやつもつけて

% 普通の再帰
atn(X, N, Sum) :-
        N > 0,
        (N mod 2 =:= 1 ->
         Sum1 is X ** (N * 2 - 1) / (N * 2 - 1) ;
         Sum1 is -X ** (N * 2 - 1) / (N * 2 - 1) ),
        N1 is N - 1,
        atn(X, N1, Sum2),
        Sum is Sum1 + Sum2, !.
atn(_, 0, 0).

% 末尾再帰
atn(X, N, Sum) :- atn_sub(X, N, Sum, 0), !.
atn_sub(_, 0, Acc, Acc).
atn_sub(X, N, Sum, Acc) :-
        An is X ** (N * 2 - 1) / (N * 2 -1),
        (N mod 2 =:= 1 ->
         Acc1 is Acc + An;
         Acc1 is Acc - An),
        N1 is N - 1,
        atn_sub(X, N1, Sum, Acc1).

atn_pi(N,R) :-
        atn(1/5,   N, Atn1),
        atn(1/239, N, Atn2),
        R is (Atn1 * 4 - Atn2) * 4.