Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the square root of a given number using bitwise operations

Tags:

algorithm

Is there an algorithm to find the square root of a given number using bitwise operations?

like image 834
dato datuashvili Avatar asked Jul 04 '10 12:07

dato datuashvili


2 Answers

There is this famous piece of code magic that computes inverse square root with a some very clever bit twiddling. It is wrongfully attributed to John Carmack - here's a deeper dig into its origin. Maybe that's what you're asking about?

I wouldn't suggest using it, though. On modern CPU's it cannot beat dedicated transcendental instructions. Your usual c++ intrinsic sqrt() would probably beat it hands down.

[Edit:] The cited article describes a general derivation method for such fast approximations, and explicitly states 'Derive a similar method for sqrt(x)' as a homework problem at its final lines. So you should be able to track its reasoning and devise a similar method for sqrt (without the reciprocal) directly.

like image 139
Ofek Shilon Avatar answered Oct 15 '22 03:10

Ofek Shilon


Wikipedia has an article about and a code too. And another wikipedia article shows an algorithm (even for roots greater than 2) that can be easily implemented in binary (so, involving operation on bits).

If you want to stick only to real bitwise operators, you have to implement + using Ands, Ors, Xors, Nots... If you want to do it on floats according to IEEE, you need more work (the first code in wikipedia could be used on the mantissa "directly", likely under certain restriction, and adjust exponent "accordingly"... you have to figure out how, however!)

like image 44
ShinTakezou Avatar answered Oct 15 '22 04:10

ShinTakezou