[erlang-questions] how: big float aithmetics (was PI calculation)

Zvi exta7@REDACTED
Thu Apr 3 01:31:14 CEST 2008


Jeff,

thank you for the solution. But I think, that mixing big integers with
floats limits precision by the float.
The more generic approach is to represent "big floats" using tuples, like
{BigInt, Exponent}.
I think it works, but I have trouble to implement division using integer
"div" operator:


%% big float arithmetics
plus({F1,E},{F2,E}) -> {F1+F2,E};
plus({F1,E1},{F2,E2}) -> 
	case E1<E2 of
		true  -> {F1+F2*pow10(E2-E1), E1};
		false -> {F1*pow10(E1-E2)+F2, E2}
	end.

minus({F1,E1},{F2,E2}) -> plus({F1,E1},{-F2,E2}).

multiply({F1,E1},{F2,E2}) -> {F1*F2,E1+E2}.

divide({F,E},{F,E}) -> {1,0};
divide({F1,E1},{F2,E2}) ->
	N1 = round(math:log10(F1)),
	N2 = round(math:log10(F2)),
	N = 2*(N1+N2), %% increase the precision?
	{F1*pow10(N) div F2, E1-E2-N}.
             %% maybe we need to scale down precision?

pow10(N) ->
	pow10(N,1).

pow10(0,Acc) -> Acc;
pow10(N,Acc) ->
	pow10(N-1,Acc*10).





jm-13 wrote:
> 
> Zvi wrote:
> 
> 
> 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.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
> 
> 

-- 
View this message in context: http://www.nabble.com/Calculate-PI-in-Erlang-faster-than-in-Matlab-tp16440056p16454022.html
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list