【问题标题】:finding all the power roots in clojure在clojure中找到所有的权力根源
【发布时间】:2012-09-08 00:47:33
【问题描述】:

这是 Finding integer power roots 的重新散列,但在 clojure 中:

如何找到一个数的所有整数根?

所以我想要一个函数:

(defn roots [ex num] .....)

调用时给出:

(roots 4 81) => [3, -3, 3i, -3i]

【问题讨论】:

    标签: clojure


    【解决方案1】:

    我为数学找到的最好的库是 apache commons 数学库

    使用添加到你的 project.clj

    [org.apache.commons/commons-math3 "3.0"]
    

    它带有一个内置的 nth-root 方法,以下可以是包装器:

    (导入 org.apache.commons.math3.complex.Complex) (定义复杂 ([re] (复数 re 0)) ([我] (Complex/valueOf re im))) (defn nth-root [#^Complex c m] (seq (.nthRoot c m))) (defmethod 打印方法 复杂的 [这个w] (print (format "(%f %fi)" (re this) (im this)))) (nth-root (复数 1 4) 6) ;; => ((1.235513 0.277543i) (0.377397 1.208757i) (-0.858115 0.931214i) (-1.235513 -0.277543i) (-0.377397 -1.208757i) (0.858115 -0.931214i)

    【讨论】:

      【解决方案2】:
      user> (defn nth-root
                [n x]
              (long (Math/pow x (/ 1.0 n))))
      #'user/nth-root
      user> (nth-root 4 81)
      3
      

      说实话,我不知道标准化的处理方式 Clojure 中的复数。您可能必须实施 您自己的Complex 记录,使用defrecord

      【讨论】:

      • 有没有 canoical java 的?
      • 我在Java 6的java.lang.Math下找不到等价的函数。不过,我认为Math/pow提供了一个令人满意的解决方案。
      • 所以问题是,实际上有四个第四根。我需要一个可以列出所有这些的函数,而不仅仅是最有可能的一个。
      • Clojure 没有内置的复数支持。为了更详细地回答,我希望您澄清您在程序中如何处理复数;导入现有的 Java 库或实现您自己的 Clojure 库。
      • 是的...我认为外部库的想法是最好的,请参阅下面的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多