ニュートン法で平方根
Prologで作る数学の世界―Prologそして集合‐位相‐群の第3章の問題。ニュートン法で平方根を求めろ。
newton(N,R) :- newton_sub(N, N, R), !. newton_sub(N, Xn, Xn) :- Xn ** 2 - N < 0.00000001. newton_sub(N, Xn, R) :- Xn1 is Xn - ((Xn ** 2 - N) /(2 * Xn)), newton_sub(N, Xn1, R).
実行結果
| ?- newton(2,R). newton(2,R). R = 1.4142135623746899 yes | ?- newton(3,R). newton(3,R). R = 1.7320508100147276 yes | ?- newton(4,R). newton(4,R). R = 2.0000000000000022 yes | ?-