[erlang-questions] math:pow(10, 1000). ===> exception error: bad argument in an arithmetic expression
Hynek Vychodil
vychodil.hynek@REDACTED
Fri Apr 10 10:36:30 CEST 2009
And here is faster O(logN) version
-module(m).
-export([pow/2, test/0]).
pow(X, N) when is_integer(N), N >= 0 -> pow(X, N, 1);
pow(X, N) when is_integer(N) -> 1 / pow(X, -N, 1);
pow(X, N) when is_float(N) -> math:pow(X, N).
pow(_, 0, P) -> P;
pow(X, N, A) when N rem 2 =:= 0 ->
pow(X * X, N div 2, A);
pow(X, N, A) -> pow(X, N - 1, A * X).
test() ->
[begin X = 1 bsl N, X = pow(2, N) end
|| N <- lists:seq(0, 10)],
[begin X = 1 / (1 bsl N), X = pow(2, -N) end
|| N <- lists:seq(1, 10)].
On Fri, Apr 10, 2009 at 9:46 AM, Kostis Sagonas <kostis@REDACTED> wrote:
> Charles Cui wrote:
> > math:pow(10,1000).
> > ** exception error: bad argument in an arithmetic expression
> > in function math:pow/2
> > called as math:pow(10,1000)
> >
> > I want to do bigint compute,such as math:pow(a,b).
> > Can Erlang do this?
>
> Sure it can. It's a Turing complete language after all...
> You just have to define it yourself.
> One possible definition appears below:
>
> -------------------------------------------------------
> -module(m).
> -export([pow/2]).
>
> -spec pow(integer(), non_neg_integer()) -> integer()
> ; (float(), non_neg_integer()) -> float().
>
> pow(X, N) when is_integer(N), N >= 0 -> pow(X, N, 1).
>
> pow(_, 0, P) -> P;
> pow(X, N, A) -> pow(X, N-1, A*X).
>
> ---------------------------------------------------------
> Eshell V5.7 (abort with ^G)
> 1> c(m).
> {ok,m}
> 2> m:pow(10, 100).
>
> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>
> Kostis
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
--
--Hynek (Pichi) Vychodil
Analyze your data in minutes. Share your insights instantly. Thrill your
boss. Be a data hero!
Try Good Data now for free: www.gooddata.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090410/45db78aa/attachment.htm>
More information about the erlang-questions
mailing list