How to resolve the algorithm Continued fraction step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Continued fraction step by step in the Prolog programming language

Table of Contents

Problem Statement

The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use

a

0

= 1

{\displaystyle a_{0}=1}

then

a

N

= 2

{\displaystyle a_{N}=2}

.

b

N

{\displaystyle b_{N}}

is always

1

{\displaystyle 1}

. For Napier's Constant, use

a

0

= 2

{\displaystyle a_{0}=2}

, then

a

N

= N

{\displaystyle a_{N}=N}

.

b

1

= 1

{\displaystyle b_{1}=1}

then

b

N

= N − 1

{\displaystyle b_{N}=N-1}

. For Pi, use

a

0

= 3

{\displaystyle a_{0}=3}

then

a

N

= 6

{\displaystyle a_{N}=6}

.

b

N

= ( 2 N − 1

)

2

{\displaystyle b_{N}=(2N-1)^{2}}

.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Continued fraction step by step in the Prolog programming language

Source code in the prolog programming language

continued_fraction :-
	% square root 2
	continued_fraction(200, sqrt_2_ab, V1),
	format('sqrt(2) = ~w~n', [V1]),

	% napier
	continued_fraction(200, napier_ab, V2),
	format('e       = ~w~n', [V2]),

	% pi
	continued_fraction(200, pi_ab, V3),
	format('pi      = ~w~n', [V3]).


% code for continued fractions
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 is A + Temp.

continued_fraction(N, Compute_ab, Tmp, V) :-
	call(Compute_ab, N, A, B),
	Tmp1 is B / (A + Tmp),
	N1 is N - 1,
	continued_fraction(N1, Compute_ab, Tmp1, V).

% specific codes for examples
% 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).


  

You may also check:How to resolve the algorithm Retrieve and search chat history step by step in the Phix programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the Ring programming language
You may also check:How to resolve the algorithm Narcissist step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Range extraction step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Totient function step by step in the MAD programming language