[erlang-questions] Multi-precision math, random number generator entropy, various other questions

Richard O'Keefe <>
Tue Jun 2 02:55:01 CEST 2009

On 1 Jun 2009, at 5:02 am, Greg Perry wrote:
> back to February 2008 mentions the problems with Erlang's bignum
> libraries and as of R13B this has not yet been fixed:
> http://www.programmersparadox.com/2008/02/05/erlang-integers/
> Any idea on when, if at any time, Erlang will get robust bignum  
> support
> (including division, power operators etc)?

math:pow/2 is EXPLICITLY documented as an interface to the C pow()
function.  There isn't any bug in integer exponentiation because
that function isn't *supposed* to be integer exponentiation.
(The last part of the math: manual page says
  Bugs As these are the C library, the bugs are the same.
  So you don't expect the math: functions to do ANYTHING that the
  C <math.h> functions don't do.)

Where did you get the idea that there was a bug in Erlang's
integer division?

I enclose a 'power' module that computes plain powers (any number
to a non-negative integral exponent) and modular powers (integers
to non-negative integral exponents modulo some value).  Of course
it could be improved.  The point is that it took 15 minutes to type
up and run a few tests.

-export([power/2, modular_power/3]).

%   power(X, N) raises X to the natural number power N.
%   For floating point exponents, see math:pow(X, Y).
%   X itself can be any kind of number.

power(X, 0) when is_number(X) ->
power(X, N) when is_number(X), is_integer(N), N > 0 ->
     rpower(X, N).

rpower(X, 1) ->
rpower(X, N) when N band 1 =:= 0 ->
     rpower(X*X, N bsr 1);
rpower(X, N) ->
     X * rpower(X, N - 1).

%   modular_power(X, N, M) returns power(X, N) rem M,
%   except that it keeps on doing remainders as it goes
%   to keep the intermediate values small.  For modular
%   powers, X must be an integer.

modular_power(X, 0, M)
   when is_integer(X), is_integer(M), M >= 1 ->
modular_power(X, N, M)
   when is_integer(X), is_integer(M), M >= 1, is_integer(N), N > 0 ->
     rmodular_power(X rem M, N, M).

rmodular_power(X, 1, _) ->
rmodular_power(X, N, M) when N band 1 =:= 0 ->
     rmodular_power((X * X) rem M, N bsr 1, M);
rmodular_power(X, N, M) ->
     (X * rmodular_power(X, N - 1, M)) rem M.

More information about the erlang-questions mailing list