Clojure平方根近似计算报错求助:无法解析aprox符号
Let's break down the issues in your code and fix them step by step:
1. Root Cause of the "Unable to resolve symbol: aprox" Error
Clojure compiles code top-to-bottom. Your msqrt function tries to call aprox before aprox is defined—this is why you're getting the symbol resolution error. We need to swap the order of the function definitions so aprox comes first.
2. Syntax & Parameter Passing Mistakes
- In
msqrt, you wrote(aprox (n 1.0 1))—this is invalid syntax. You meant to passn,1.0(initial approximation), and1(starting iteration count) as separate arguments, so it should be(aprox n 1.0 1). - Inside the
aproxfunction, your recursive calls have mixed-up parameter order. For example,(aprox n part (+ part 1))is passingpartas the approximation value instead of the currentprox—that breaks the iteration logic entirely.
3. Incorrect Newton-Raphson Formula
The standard iterative formula for square root approximation (Newton-Raphson method) is:
x_{k+1} = (x_k + n/x_k) / 2
Your current formula was miswritten; we'll fix that to match the correct logic.
Fixed Code
;; Define the helper function first so msqrt can reference it (defn aprox [n prox part] (if (= part 20) prox ;; Calculate next approximation using the correct formula, then recurse (let [next-prox (/ (+ prox (/ n prox)) 2)] (aprox n next-prox (+ part 1))))) ;; Define msqrt to kick off the iteration with initial values (defn msqrt [n] (aprox n 1.0 1)) ;; Test with your sample input (msqrt 9)
How It Works
- We start with an initial approximation of
1.0and begin counting iterations from1. - For each step until we hit the 20th iteration, we compute the next approximation using the Newton-Raphson formula.
- Once we reach the 20th iteration, we return the current approximation value.
When you run this code, it will correctly converge to the square root of 9 (you'll see it hits 3.0 well before the 20th iteration) without any compilation errors.
内容的提问来源于stack exchange,提问作者FatTommy

