[erlang-questions] How to calculate series expansion e^x

Richard A. O'Keefe <>
Wed Mar 4 03:29:54 CET 2015


On 4/03/2015, at 10:32 am, Harit Himanshu <> wrote:
> 
> e_x(X) ->
>   1 + lists:sum([math:pow(X, N) / fact(N) || N <- lists:seq(1, 9)]).

If you want *clarity*, then you should not make 1 a special case.
1 is just math:pow(X, 0)/fact(0), so

    lists:sum([math:pow(X, N) / fact(N) || N <- lists:seq(0, 9)]).

does the job more simply.

BUT either way, this is inefficient and inaccurate.
I explained Horner's rule.

It is also uncommented.
In my earlier reply I pointed out that this is sort of OK
for small values of X but grossly inaccurate for values of
X >= 1.
There desperately needs to be a comment explaining this limitation.

> 
> fact(N) ->
>   case N of
>     0 -> 1;
>     1 -> 1;
>     _ -> N * fact(N - 1)
>   end.

This is problematic in several ways.
First, if N < 0, it will loop forever instead of failing sensibly.
Second, if N is a float but not integral, the factorial function
is indeed defined, but _this_ function will loop forever.

%   fact(N) = N! for non-negative integer N.
%   This module only needs 0 <= N <= 9.

fact(N) when is_integer(N), N >= 0 ->
    fact_loop(1, N, 1).

fact_loop(A, B, R) when A < B ->
    fact_loop(A+1, B-1, (A*B)*R);
fact_loop(A, A, R) ->
    A*R;
fact_loop(_, _, R) ->
    R.

(This is adapted from my Smalltalk system.  It's not the _best_
way to implement factorial, but it's _better_ than the naive loop.)
http://www.luschny.de/math/factorial/FastFactorialFunctions.htm
is an interesting page on computing factorials.



More information about the erlang-questions mailing list