[erlang-questions] Calculate PI in Erlang faster than in Matlab

jm jeffm@REDACTED
Wed Apr 2 07:42:13 CEST 2008


Zvi wrote:

> If anyone can improve parallel version not only in speed, but also in making
> it clear, so it will be fitting presentation / textbook style.
> Also, I want to modify HOF samples to use plists module.
> 
> If anyone can give me pointers, how modify this example to use big integer
> arithmetics, i.e. to calculate first N digits of PI.
> 

Here's an example of how to do fixed point arithmatic.

change

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 5. serial - tail recursion - decrement index
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
calc_pi(serial_decr,N) ->
         calc_pi1(N,1/N,0);


and

calc_pi1(0,Step,Sum) -> Step*Sum;
calc_pi1(I,Step,Sum) ->
         X=Step*(I-0.5),
         V=4.0/(1.0+X*X),
         calc_pi1(I-1,Step,Sum+V).


to

calc_pi_fixedpoint(serial_decr, N, DecimalPlaces) ->
         calc_pi1(N, 1/N, 0, math:pow(10,DecimalPlaces));


calc_pi1(0, Step, Sum, _Numerator) -> 4*Sum div round(1/Step);
calc_pi1(I, Step, Sum, Numerator) ->
%%      io:format("I ~p Step ~p Sum ~p Numerator ~p~n",
%%                [I, Step, Sum, Numerator]),
         X = Step*(I-0.5),
         V = round(Numerator / (1.0+X*X)), %% integer by rounding
         calc_pi1(I-1, Step, Sum+V, Numerator).


There may be better ways of course. I'll leave converting the rest as an 
exercise :-).

Would you care to add a distributed (multi node) example as well?

The other thought I had was that instead of just having N recursive 
calls add a tolerance, Epsilon, which will stop the evaluation when two 
calls differ by less than Epsilon.

Jeff.



More information about the erlang-questions mailing list