我该如何在Clojure中进行指数运算?目前我只需要整数指数,但这个问题也适用于分数。
我该如何在Clojure中进行指数运算?目前我只需要整数指数,但这个问题也适用于分数。
使用 reduce 的简单一行代码:
(defn pow [a b] (reduce * 1 (repeat b a)))
使用 clojure.math.numeric-tower
,之前被称为 clojure.contrib.math
。
(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))
我个人使用:
(defn pow [x n] (reduce *' (repeat n x)))
注意星号后面的撇号(')。
适用于所有大小的整数。
注意:对于某些实现来说,这可能有点慢。 (time (pow 2 200000))在我的系统上解决需要1.2秒。
尝试
(defn pow [x n]
(loop [x x n n r 1]
(cond
(= n 0) r
(even? n) (recur (* x x) (/ n 2) r)
:else (recur x (dec n) (* r x)))))
对于一个尾递归的O(log n)解决方案,如果你想自己实现它(仅支持正整数)。显然,更好的解决方案是使用其他人指出的库函数。
clojure.contrib.genric.math-functions 怎么样?
在 clojure.contrib.generic.math-functions 库中有一个 pow 函数。它只是一个调用 Math.pow 的宏,更像是一种“clojureish”的调用 Java math 函数的方式。