Update
This commit is contained in:
parent
5134e55998
commit
a4a9624abe
11 changed files with 2078 additions and 1825 deletions
39
sqrt.md
39
sqrt.md
|
@ -62,7 +62,44 @@ unsigned int sqrtInt(unsigned int x)
|
|||
}
|
||||
```
|
||||
|
||||
TODO: Heron's method
|
||||
But now let's take a look at **maybe even a better algorithm** -- it only gives an approximation, however it's pretty accurate and we may modify it to give a precise value by simply adjusting the estimate at the end. The advantage is that the approximation only uses bit shifts, no multiplication! This can be crucial on some simple platforms where multiplication may be expensive. Furthermore the algorithm is pretty simple, it works like this: given input number *x*, we may imagine we have a rectangle of size 1 times *x*; now we can try to make it into square by doubling the first side and halving the other. If we get equal sides, the side length is the square root. Of course we don't always iterate to the same side sizes -- if the first side gets bigger than the other, we stop and simply average them -- and that's it! Here's the code:
|
||||
|
||||
{ I remember I came up with a simple form of this algorithm when I was still in elementary school, however it's pretty obvious so it probably already exists, I didn't bother checking. Measuring the speed of this the pure approximation is very fast, I measured it basically at the same speed as the stdlib float square root; the exact version is of course considerably slower -- anyway for lower input values I measured it even faster than the binary search, however for higher values not anymore. ~drummyfish }
|
||||
|
||||
```
|
||||
unsigned int sqrtIntApprox(unsigned int x)
|
||||
{
|
||||
unsigned int a = 1;
|
||||
|
||||
while (x > a)
|
||||
{
|
||||
a <<= 1;
|
||||
x >>= 1;
|
||||
}
|
||||
|
||||
return (a + x) >> 1;
|
||||
}
|
||||
|
||||
unsigned int sqrtIntExact(unsigned int x)
|
||||
{
|
||||
unsigned int a = 1, b = x;
|
||||
|
||||
while (b > a)
|
||||
{
|
||||
a <<= 1;
|
||||
b >>= 1;
|
||||
}
|
||||
|
||||
a = (a + b) >> 1;
|
||||
|
||||
while (a * a > x) // iterate to exact value
|
||||
a--;
|
||||
|
||||
return a;
|
||||
}
|
||||
```
|
||||
|
||||
TODO: Heron's method?
|
||||
|
||||
The following is a **non-iterative [approximation](approximation.md)** of integer square root in [C](c.md) that has acceptable accuracy to about 1 million (maximum error from 1000 to 1000000 is about 7%): { Painstakingly made by me. This one was even faster than the stdlib function! ~drummyfish }
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue