Continued fraction: Difference between revisions
Content added Content deleted
(add lambdatalk code) |
|||
Line 2,263: | Line 2,263: | ||
Pi: 3.141592654 |
Pi: 3.141592654 |
||
</pre> |
</pre> |
||
=={{header|Picat}}== |
|||
For Pi a test is added with a higher precision (200 -> 2000) to get a better result. |
|||
First a recursive version (based on Prolog's implementation): |
|||
<lang Picat>go => |
|||
% square root 2 |
|||
continued_fraction(200, sqrt_2_ab, V1), |
|||
printf("sqrt(2) = %w (diff: %0.15f)\n", V1, V1-sqrt(2)), |
|||
% napier |
|||
continued_fraction(200, napier_ab, V2), |
|||
printf("e = %w (diff: %0.15f)\n", V2, V2-math.e), |
|||
% pi |
|||
continued_fraction(200, pi_ab, V3), |
|||
printf("pi = %w (diff: %0.15f)\n", V3, V3-math.pi), |
|||
% get a better precision |
|||
continued_fraction(20000, pi_ab, V3b), |
|||
printf("pi = %w (diff: %0.15f)\n", V3b, V3b-math.pi), |
|||
nl. |
|||
continued_fraction(N, Compute_ab, V) ?=> |
|||
continued_fraction(N, Compute_ab, 0, V). |
|||
continued_fraction(0, Compute_ab, Temp, V) ?=> |
|||
call(Compute_ab, 0, A, _), |
|||
V = A + Temp. |
|||
continued_fraction(N, Compute_ab, Tmp, V) => |
|||
call(Compute_ab, N, A, B), |
|||
Tmp1 = B / (A + Tmp), |
|||
N1 = N - 1, |
|||
continued_fraction(N1, Compute_ab, Tmp1, V). |
|||
% definitions for square root of 2 |
|||
sqrt_2_ab(0, 1, 1). |
|||
sqrt_2_ab(_, 2, 1). |
|||
% definitions for napier |
|||
napier_ab(0, 2, _). |
|||
napier_ab(1, 1, 1). |
|||
napier_ab(N, N, V) :- |
|||
V is N - 1. |
|||
% definitions for pi |
|||
pi_ab(0, 3, _). |
|||
pi_ab(N, 6, V) :- |
|||
V is (2 * N - 1)*(2 * N - 1).</lang> |
|||
Output: |
|||
<pre> |
|||
sqrt(2) = 1.414213562373095 (diff: 0.000000000000000) |
|||
e = 2.718281828459046 (diff: 0.000000000000000) |
|||
pi = 3.141592622804847 (diff: -0.000000030784946) |
|||
pi = 3.141592653589762 (diff: -0.000000000000031) |
|||
</pre> |
|||
Then an iterative version (from Python's Fast Iterative version) |
|||
<lang Picat>continued_fraction_it(Fun, N) = Ret => |
|||
Temp = 0.0, |
|||
foreach(I in N..-1..1) |
|||
[A,B] = apply(Fun,I), |
|||
Temp := B / (A + Temp) |
|||
end, |
|||
F = apply(Fun,0), |
|||
Ret = F[1] + Temp. |
|||
fsqrt2(N) = [cond(N > 0, 2, 1),1]. |
|||
fnapier(N) = [cond(N > 0, N,2), cond(N>1,N-1,1)]. |
|||
fpi(N) = [cond(N>0,6,3), (2*N-1) ** 2].</lang> |
|||
Which has exactly the same output as the recursive version. |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |