I was working through a problem at <a href="http://programmingpraxis.com/2009/12/18/calculating-logarithms/">Programming Praxis</a>, and was happy to find that my solution closely matched the &quot;approved&quot; solution, but I noted a fairly big difference in our styles, and I thought I&#39;d seek the community&#39;s feedback...<br>
<br>To illustrate, I present part of the problem, that solves for square roots by recursion using Newton&#39;s method:<br><br>x &lt;- x - (y - x^2)/2x<br><br>I now show the &quot;approved&quot; solution, and my own, both edited a bit to cleanly present my questions.<br>
<br>(define epsilon 1e-7)<br><br>; The &quot;approved&quot; solution<br>(define (approved-sqrt y)<br>  (let loop [(x (/ y 2))]<br>    (if (&lt; (abs (- (* x x) y)) epsilon) x<br>      (loop (- x (/ (- (* x x) y) (+ x x)))))))<br>
<br>; My solution<br>(define (my-sqrt y)<br>  (let loop [(x (/ y 2))]<br>    (let [(error (- y (* x x)))]<br>      (if (&lt; (abs error) epsilon) x<br>          (loop (+ x (/ error 2 x)))))))<br><br>I haven&#39;t timed the two, as I&#39;m more interested in the &quot;big picture&quot; than this particular function. <br>
Question 1: Is my use of the temporary &quot;error&quot; worth it in terms of performance (the approved solution calculates (* x x) twice)? If it&#39;s not worth it, how big does the calculation have to become before it does? Can the compiler make such a temporary live only in a register?<br>
    Question 1a: How creeped are you by my changing the meaning of error for these few lines? I find myself doing stuff like this, in the name of my idea of readability, a lot.<br>Question 2: The approved solution favored (/ ... (+ x x)) over my (/ ... 2 x). Cost of division versus readability. Wasn&#39;t a conscious decision of mine at the time, but now I&#39;m curious. How smart is the compiler when presented with a division by 2? With multiple recalls of the same value?<br>
<br>Thanks for any comments.<br> <br>Pat<br><br>