/ramesh
at i27...@risc1.ecn.missouri.edu
also at http://www.missouri.edu/~uc625505
>I have a question regarding finding natural logarithm of a number in prolog.
>How can you write a small prolog code to find natural logarithm of a number ? Is
>there any way out? Thanks for any help regarding this.
If your Prolog provides a log10 predicate then you can use the change
of base of rule to calculate the log base e:-
ln(X) = log10(X)/log10(e)
i.e. in Prolog,
ln(X,Result):-
Result is log10(X)/0.4342944
However, if this is not the case, and assuming that floating point
calculations are supported, you could always resort to a Maclaurin
series expansion (ln(1+X) = X - (X^2)/2 + (X^3)/3 +...)
%******************************************************************
% ln(X,Result): The natural logarithm of X evaluated to an accuracy
% of 3 d.p. is Result.
ln(X,Result):-
X > 0,
X =< 1,
X1 is X - 1,
sum_of_series(X1,X1,1,0,Result).
sum_of_series(_,XtoN,N,Result,Result):-
abs(XtoN/N) < 0.0005.
sum_of_series(X,XtoN,N,Sum,Result):-
Term is XtoN/N,
abs(Term) >= 0.0005,
NewSum is Sum + Term,
Nplus1 is N + 1,
XtoNplus1 is -X * XtoN,
sum_of_series(X,XtoNplus1,Nplus1,NewSum,Result).
%********************************************************
You also need to have an evaluable arithmetic predicate abs for this
to work. It wouldn't be difficult to write it yourself.
The problem is of course that the expansion is valid (convergent) only
for 0 < X =< 1
Hope that's some help.
Regards,
Peter.
The expansion for natural logs is :
ln(1+x)=x -x^2/2 +x^3/3 - x^4/4 + x^5/5 ......
(for |x|<1)
To implement this in prolog, first create a function 'term' which
when called for index n, calculates x^n/n and adds/subtracts it to
term(n+1). For term(m), where m is the maximum term you wish to use,
return 0 to stop the recursion. If your prolog can't calculate powers,
use a recursive function to calculate them. You may need two almost
identical 'terms' handling the positive and negative alternate additions.
I haven't actually written such a program, but it seems feasible.
John August.