Hi, this is my first forum and I want to do it: quick way to calculate the square root in c ++ with floating data types. These types of functions are very useful to gain some CPU time, especially when used continuously. I will show you 3 similar functions and indicate the advantages and disadvantages of each of them. The last of these three functions was written by me. If you notice that the writing is a bit out of grammar, it is because I do not speak English and I am using a support tool. My native language is Spanish. Well, let's start:
The First method is very famous was used in the video game quake III arena and you can find a reference in Wikipedia as: :https://en.wikipedia.org/wiki/Fast_inverse_square_root.
The Function was optimized for improvements in computing times.
float sqrt1(const float &n)
{
static union{int i; float f;} u;
u.i = 0x5F375A86 - (*(int*)&n >> 1);
return (int(3) - n * u.f * u.f) * n * u.f * 0.5f;
}
-Advantages:
* When Root of 0 is calculated the function returns 0.
* The convergence of the function is acceptable enough for games.
* It generates very good times.
* The Reciprocal of the root can be calculated by removing the second “n” from the third line. According to the property of: 1 / sqrt (n) * n = sqrt (n).
-Disadvantages:
* Convergence decreases when the root to be calculated is very large.
The second method is not as famous as the first. But it does the same function calculate the root.
float sqrt2(const float& n)
{
union {int i; float f;} u;
u.i = 0x1FB5AD00 + (*(int*)&n >> 1);
u.f = n / u.f + u.f;
return n / u.f + u.f * 0.25f;
}
-Advantages:
* The convergence of the function is high enough to be used in applications other than games.
-Disadvantages:
* Computing times are much larger.
* The square root of “0” is a number very close to “0” but never “0”.
* The division operation is the bottleneck in this function. because the division operation is more expensive than the other arithmetic operations of Arithmetic Logic Units (ALU).
The third method takes certain characteristics of the two previous methods.
float sqrt3(const float& n)
{
static union {int i; float f;} u;
u.i = 0x2035AD0C + (*(int*)&n >> 1);
return n / u.f + u.f * 0.25f;
}
Advantages:
* The convergence of the function is greater than that of the first method.
* Generates times equal to or greater than the first method.
Disadvantages:
* The square root of “0” is a number very close to “0” but never “0”.
The 3 previous methods have something in common.
They are based on the definition of the Newton-Raphson Method. according to the function of the square root > f (x) = x ^ 2 - s.
well thanks to you for reading my forum.
well thanks to you for reading my forum.