牛顿法在Clojure中的实现

我正在尝试在Clojure中实现牛顿法来解决方程f(x)= 0。函数采用以下参数:f(函数)f'(函数的导数)n(迭代次数)= 10,x0(初始猜测)= 10。

 (defn newtons-method [f f' n x0]
     (if (<= (f x0))
         n
         (newtons-method f f' (- x0 (/ (f x0) (f' x0))) (+ n 1)))
     )

我得到10的输出,但是想要x的最终解和f(x)的结果,我知道10是错误的,因为我的函数f及其派生给出了正确的答案,所以我假设我搞砸了迭代中的某个地方

mfpaaa 回答:牛顿法在Clojure中的实现

好吧,您似乎至少有两个问题。 首先,您的条件将始终返回true(假设### plot first three datasets with different color reset session myColor(n) = n==0 ? 0xff0000 : n==1 ? 0x00ff00 : n==2 ? 0x0000ff : 0xcccccc plot "plot_data.dat" u 1:2:(myColor(column(-1))) w l lc rgb var notitle ### end of code 返回一个数值),因此这可能不是您想要的。

此外,为了正确地在clojure中实现递归函数,您应该查看recur,否则可能会遇到堆栈溢出(在这种情况下不太可能,但仍然如此)

另一件事是,不做(f x0),而是习惯使用(+ n 1)

本文链接:https://www.f2er.com/3130049.html

大家都在问