c++ practical computational complexity of SQRT()

前端 未结 3 973
长情又很酷
长情又很酷 2020-12-15 12:06

What is the difference in CPU cycles (or, in essence, in \'speed\') between

 x /= y;

and

 #include 
 x = sqr         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 12:45

    If the square root function isn't implemented in special hardware or software, most library functions would calculate it using Newton's method, which converges quadratically.

    Newton's method is an iterative method: you make an initial guess, calculate a trial result, and use that for the next guess. You repeat until you think you have a result that's "close enough." It so happens that you can prove how many iterations you need with square root. Every time through the cycle you get another two digits of accuracy, so most implementations will converge to the precision limit of doubles in 8-9 cycles.

    If you read this carefully, you'll see that the iterative Newton's method is doing two subtractions, one multiplication, and one division per iteration.

提交回复
热议问题