less_retarded_wiki/sqrt.md

32 lines
2.1 KiB
Markdown
Raw Normal View History

2022-09-19 08:56:30 +02:00
# Square Root
2023-08-26 22:09:20 +02:00
Square root (sometimes shortened to *sqrt*) of number *a* is such a number *b* that *b^2 = a*, for example 3 is a square root of 9 because 3^2 = 9. Finding square root is one of the most basic and important operations in [math](math.md) and [programming](programming.md), e.g. for computing [distances](distance.md), solving [quadratic equations](quadratic_equation.md) etc. Square root is a special case of finding Nth [root](root.md) of a number for N = 2. Square root of a number doesn't have to be a whole number; in fact if the square isn't a whole number, it is always an [irrational number](irrational_number.md) (i.e. it can't be expressed as a fraction of two integers, for example square root of [two](two.md) is approximately 1.414...); and it doesn't even have to be a real number (e.g. square root of -1 is [i](i.md)). Strictly speaking there may exist multiple square roots of a number, for example both 5 and -5 are square roots of 25 -- the positive square root is called **principal square root**; principal square root of *x* is the same number we get when we raise *x* to 1/2, and this is what we are usually interested in -- from now on by *square root* we will implicitly mean *principal square root*. Programmers write *square root of x* as `sqrt(x)` (which should give the same result as raising to 1/2, i.e. `pow(x,0.5)`), mathematicians write it as:
```
_ 1/2
\/x = x
```
TODO
## Programming
2022-09-19 08:56:30 +02:00
TODO
2023-08-26 22:09:20 +02:00
Within desired precision square root can be relatively quickly computed iteratively by [binary search](binary_search.md). Of course if we need extreme speed, we may use a [look up table](lut.md) with precomputed values.
2022-09-19 08:56:30 +02:00
2023-08-26 22:09:20 +02:00
TODO: C code for binary search
2022-09-19 08:56:30 +02:00
2023-08-26 22:09:20 +02:00
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. ~drummyfish }
2022-09-19 08:56:30 +02:00
```
int32_t sqrtApprox(int32_t x)
{
return
(x < 1024) ?
(-2400 / (x + 120) + x / 64 + 20) :
((x < 93580) ?
(-1000000 / (x + 8000) + x / 512 + 142) :
(-75000000 / (x + 160000) + x / 2048 + 565));
}
```