How can I do exponentiation in clojure? For now I'm only needing integer exponentiation, but the question goes for fractions too.
相关问题
- Better Sequence Duplicate Remover
- Installation of Leiningen 2.X in Mac OS X
- Questions about Lists and other stuff in Clojure
- How do I add CORS to a compojure-api app?
- How do I use Clojure in Android Studio using Gracl
相关文章
- Factor Clojure code setting many different fields
- Does learning one Lisp help in learning the other?
- Better way to nest if-let in clojure
- Idiomatic approach for structuring Clojure source
- Is a “transparent” macrolet possible?
- Detect operating system in Clojure
- Using quote in Clojure
- Raise 10 to a power in javascript, are there bette
When this question was originally asked, http://clojure.github.com/clojure-contrib/math-api.html#clojure.contrib.math/expt is where the official library function to do this lived. Since then, it has moved to https://github.com/clojure/math.numeric-tower/blob/master/src/main/clojure/clojure/math/numeric_tower.clj#L80
I think this would work too:
How about clojure.contrib.genric.math-functions
There is a pow function in the clojure.contrib.generic.math-functions library. It is just a macro to Math.pow and is more of a "clojureish" way of calling the Java math function.
http://clojure.github.com/clojure-contrib/generic.math-functions-api.html#clojure.contrib.generic.math-functions/pow
If you really need a function and not a method you can simply wrap it:
And in this function you can cast it to
int
or similar. Functions are often more useful that methods because you can pass them as parameters to another functions - in this casemap
comes to my mind.If you really need to avoid Java interop, you can write your own power function. For example, this is a simple function:
That calculates power for integer exponent (i.e. no roots).
Also, if you are dealing with large numbers, you may want to use
BigInteger
instead ofint
.And if you are dealing with very large numbers, you may want to express them as lists of digits, and write your own arithmetic functions to stream over them as they calculate the result and output the result to some other stream.
Use
clojure.math.numeric-tower
, formerlyclojure.contrib.math
.API Documentation
Implementation of "sneaky" method with tail recursion and supporting negative exponent: