How to do exponentiation in clojure?

前端 未结 13 1819
执笔经年
执笔经年 2021-01-30 12:32

How can I do exponentiation in clojure? For now I\'m only needing integer exponentiation, but the question goes for fractions too.

13条回答
  •  不知归路
    2021-01-30 12:55

    If you really need a function and not a method you can simply wrap it:

     (defn pow [b e] (Math/pow b e))
    

    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 case map 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:

     (defn pow [n p] (let [result (apply * (take (abs p) (cycle [n])))]
       (if (neg? p) (/ 1 result) result)))
    

    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 of int.

    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.

提交回复
热议问题