forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfastsqrt.cpp
More file actions
37 lines (27 loc) · 650 Bytes
/
fastsqrt.cpp
File metadata and controls
37 lines (27 loc) · 650 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// CPP program for fast inverse square root.
#include<bits/stdc++.h>
using namespace std;
// function to find the inverse square root
float inverse_rsqrt( float number )
{
const float threehalfs = 1.5F;
float x2 = number * 0.5F;
float y = number;
// evil floating point bit level hacking
long i = * ( long * ) &y;
// value is pre-assumed
i = 0x5f3759df - ( i >> 1 );
y = * ( float * ) &i;
// 1st iteration
y = y * ( threehalfs - ( x2 * y * y ) );
// 2nd iteration, this can be removed
// y = y * ( threehalfs - ( x2 * y * y ) );
return y;
}
// driver code
int main(){
int n = 256;
float f = inverse_rsqrt(n);
cout << f << endl;
return 0;
}