How to do exponentiation in clojure?

2019-03-08 12:16发布

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

13条回答
乱世女痞
2楼-- · 2019-03-08 13:04
▲ chillily
3楼-- · 2019-03-08 13:05

I think this would work too:

(defn expt [x pow] (apply * (repeat pow x)))
查看更多
The star\"
4楼-- · 2019-03-08 13:06

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

查看更多
做自己的国王
5楼-- · 2019-03-08 13:07

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.

查看更多
我只想做你的唯一
6楼-- · 2019-03-08 13:07

Use clojure.math.numeric-tower, formerly clojure.contrib.math.


API Documentation


(ns user
  (:require [clojure.math.numeric-tower :as m]))

(defn- sqr
  "Uses the numeric tower expt to square a number"
  [x]
  (m/expt x 2))
查看更多
别忘想泡老子
7楼-- · 2019-03-08 13:08

Implementation of "sneaky" method with tail recursion and supporting negative exponent:

(defn exp
  "exponent of x^n (int n only), with tail recursion and O(logn)"
   [x n]
   (if (< n 0)
     (/ 1 (exp x (- n)))
     (loop [acc 1
            base x
            pow n]
       (if (= pow 0)
         acc                           
         (if (even? pow)
           (recur acc (* base base) (/ pow 2))
           (recur  (* acc base) base (dec pow)))))))
查看更多
登录 后发表回答