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 "approved" solution, but I noted a fairly big difference in our styles, and I thought I'd seek the community's feedback...<br>
<br>To illustrate, I present part of the problem, that solves for square roots by recursion using Newton's method:<br><br>x <- x - (y - x^2)/2x<br><br>I now show the "approved" solution, and my own, both edited a bit to cleanly present my questions.<br>
<br>(define epsilon 1e-7)<br><br>; The "approved" solution<br>(define (approved-sqrt y)<br> (let loop [(x (/ y 2))]<br> (if (< (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 (< (abs error) epsilon) x<br> (loop (+ x (/ error 2 x)))))))<br><br>I haven't timed the two, as I'm more interested in the "big picture" than this particular function. <br>
Question 1: Is my use of the temporary "error" worth it in terms of performance (the approved solution calculates (* x x) twice)? If it'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't a conscious decision of mine at the time, but now I'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>