1
1
"""
2
- Fast inverse square root.
2
+ Fast inverse square root (1/sqrt(x)) using the Quake III algorithm .
3
3
Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root
4
+ Accuracy: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy
4
5
"""
5
6
6
7
import struct
7
8
8
9
9
10
def fast_inverse_sqrt (number : float ) -> float :
10
11
"""
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.
12
+ Compute the fast inverse square root of a floating-point number using the famous
13
+ Quake III algorithm.
15
14
16
15
:param float number: Input number for which to calculate the inverse square root.
17
16
:return float: The fast inverse square root of the input number.
18
17
19
18
Example:
20
19
>>> fast_inverse_sqrt(10)
21
20
0.3156857923527257
22
-
23
21
>>> fast_inverse_sqrt(4)
24
22
0.49915357479239103
25
-
23
+ >>> fast_inverse_sqrt(4.1)
24
+ 0.4932849504615651
26
25
>>> fast_inverse_sqrt(0)
27
26
Traceback (most recent call last):
28
27
...
29
28
ValueError: Input must be a positive number.
30
-
31
29
>>> fast_inverse_sqrt(-1)
32
30
Traceback (most recent call last):
33
31
...
34
32
ValueError: Input must be a positive number.
33
+ >>> from math import isclose, sqrt
34
+ >>> all(isclose(fast_inverse_sqrt(i), 1 / sqrt(i), rel_tol=0.00132)
35
+ ... for i in range(50, 60))
36
+ True
35
37
"""
36
38
if number <= 0 :
37
39
raise ValueError ("Input must be a positive number." )
@@ -42,6 +44,11 @@ def fast_inverse_sqrt(number: float) -> float:
42
44
43
45
44
46
if __name__ == "__main__" :
45
- import doctest
47
+ from doctest import testmod
48
+
49
+ testmod ()
50
+ # https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy
51
+ from math import sqrt
46
52
47
- doctest .testmod (verbose = True )
53
+ for i in range (5 , 101 , 5 ):
54
+ print (f"{ i :>3} : { (1 / sqrt (i )) - fast_inverse_sqrt (i ):.5f} " )
0 commit comments