How to resolve the algorithm Calculating the value of e step by step in the Prolog programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Calculating the value of e step by step in the Prolog programming language

Table of Contents

Problem Statement

Calculate the value of   e.

(e   is also known as   Euler's number   and   Napier's constant.)

See details: Calculating the value of e

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Calculating the value of e step by step in the Prolog programming language

Source code in the prolog programming language

% Calculate the value e = exp 1
%   Use Newton's method: x0 = 2; y = x(2 - ln x)

tolerance(1e-15).

exp1_iter(L) :-
    lazy_list(newton, 2, L).

newton(X0, X1, X1) :-
    X1 is X0*(2 - log(X0)).

e([X1, X2|_], X1) :- tolerance(Eps), abs(X2 - X1) < Eps.
e([_|Xs], E) :- e(Xs, E).

main :-
    exp1_iter(Iter),
    e(Iter, E),
    format("e = ~w~n", [E]),
    halt.

?- main.


% John Devou: 26-Nov-2021
% Simple program to calculate e up to n decimal digits.
% Works fast for n ≤ 1 000 000.

l(M,F,L,S):- F > L -> S is M-1; M_ is M+1, F_ is F*M_, l(M_,F_,L,S).

e(S,X,Y,N,E):- S < 2 -> E is div(X*10**N,Y);
    S_ is S-1, X_ is X+Y, Y_ is S*Y, e(S_,X_,Y_,N,E).

main:-
    get_time(Start),				% start computation
    current_prolog_flag(argv,[X|_]),		% read arguments
    atom_number(X,N),				% convert first argument to number
    L is 3*10**(N+1), l(1,1,L,S),		% find the smallest S, such that (S+1)! > 3*10^(N+1)
    e(S,0,1,N,E),				% compute decimal part of series 1/2! + 1/3! + ... + 1/S!
    get_time(End),				% finish computation
    format("e = 2.~d\n",E),			% show number
    format("Computed in ~f sec",End- Start),	% show computation time
    halt.

?- main.


  

You may also check:How to resolve the algorithm Loops/For step by step in the Scala programming language
You may also check:How to resolve the algorithm A+B step by step in the AWK programming language
You may also check:How to resolve the algorithm Return multiple values step by step in the C programming language
You may also check:How to resolve the algorithm Hello world/Newbie step by step in the Fortran programming language
You may also check:How to resolve the algorithm Bitwise IO step by step in the Wren programming language