Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Clojure中迭代帮助_Clojure_Newtons Method - Fatal编程技术网

在Clojure中迭代帮助

在Clojure中迭代帮助,clojure,newtons-method,Clojure,Newtons Method,我是Clojure的新手,正在尝试使用内置的迭代编写牛顿方法函数。我尝试了几种方法,得到了下面的代码。你知道为什么这只是返回空的paren吗?我也乐于接受新的想法 (defn within-tol? "returns true if the guess is within the given tolerance" [guess x tolerance] (< (abs (- (square guess) x)) tolerance)) (defn next-guess

我是Clojure的新手,正在尝试使用内置的迭代编写牛顿方法函数。我尝试了几种方法,得到了下面的代码。你知道为什么这只是返回空的paren吗?我也乐于接受新的想法

(defn within-tol? 
  "returns true if the guess is within the given tolerance"
  [guess x tolerance]
  (< (abs (- (square guess) x)) tolerance))

(defn next-guess 
  [guess x] 
  (average guess (/ x guess)))

(defn average
  [x y]
  (float (/ (+ x y) 2)))

(defn abs 
  [x]
  (cond
    (< x 0) (- x)
    :else x))

(defn square 
  [x]
  (* x x))

 (defn sqrt-iter
  [guess x tolerance]
  (if (within-tol? guess x tolerance) guess
    (sqrt-iter (next-guess guess x) x tolerance)))

 (defn sqrt 
   [guess x tolerance]
   (take-while #(within-tol? % x tolerance) (iterate #((sqrt % x tolerance)) guess)))
(定义在tol中?
“如果猜测在给定公差范围内,则返回true”
[猜测x公差]
(<(绝对值(-(平方猜测)x))公差)
(下一个猜测
[猜x]
(平均猜测(/x猜测)))
(定义平均值)
[x y]
(浮动(/(+xy)2)))
(defn abs
[x]
(续)
(
似乎您的
sqrt
是错误的,因为它没有使用
下一个猜测

试试看

(defn sqrt 
  [guess x tolerance]
  (first (drop-while #(not (within-tol? % x tolerance))
                     (iterate #(next-guess % x) guess))))
例如:

(sqrt 1 169 0.01) => 13.0

你能举一个例子说明你是如何测试你的功能的吗?还有一些函数定义缺失(至少
average
square
)。一个示例调用是:(sqrt 1.4 2 0.01)sqrt不应该在某个点调用next guess吗?这很有意义!谢谢