File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Fast inverse square root.
3
+ Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root
4
+ """
5
+
6
+ import struct
7
+
8
+
9
+ def fastInvSqrt (x ):
10
+ """
11
+ Calculate the fast inverse square root of a number.
12
+
13
+ This function computes the fast inverse square root of a floating-point number
14
+ using the famous Quake III algorithm, originally developed by id Software.
15
+
16
+ :param float x: The input number for which to calculate the inverse square root.
17
+ :return float: The fast inverse square root of the input number.
18
+
19
+ Example:
20
+ >>> fastInvSqrt(10)
21
+ 0.3156857923527257
22
+
23
+ >>> fastInvSqrt(4)
24
+ 0.49915357479239103
25
+ """
26
+ i = struct .unpack ('>i' , struct .pack ('>f' , x ))[0 ]
27
+ i = 0x5f3759df - (i >> 1 )
28
+ y = struct .unpack ('>f' , struct .pack ('>i' , i ))[0 ]
29
+ return y * (1.5 - 0.5 * x * y * y )
30
+
31
+ if __name__ == "__main__" :
32
+ import doctest
33
+
34
+ doctest .testmod (verbose = True )
You can’t perform that action at this time.
0 commit comments