Skip to content

Commit aeae0a8

Browse files
authored
Update fast_inverse_sqrt.py
1 parent 68a09b7 commit aeae0a8

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

maths/fast_inverse_sqrt.py

+17-10
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
11
"""
2-
Fast inverse square root.
2+
Fast inverse square root (1/sqrt(x)) using the Quake III algorithm.
33
Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root
4+
Accuracy: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy
45
"""
56

67
import struct
78

89

910
def fast_inverse_sqrt(number: float) -> float:
1011
"""
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.
1514
1615
:param float number: Input number for which to calculate the inverse square root.
1716
:return float: The fast inverse square root of the input number.
1817
1918
Example:
2019
>>> fast_inverse_sqrt(10)
2120
0.3156857923527257
22-
2321
>>> fast_inverse_sqrt(4)
2422
0.49915357479239103
25-
23+
>>> fast_inverse_sqrt(4.1)
24+
0.4932849504615651
2625
>>> fast_inverse_sqrt(0)
2726
Traceback (most recent call last):
2827
...
2928
ValueError: Input must be a positive number.
30-
3129
>>> fast_inverse_sqrt(-1)
3230
Traceback (most recent call last):
3331
...
3432
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
3537
"""
3638
if number <= 0:
3739
raise ValueError("Input must be a positive number.")
@@ -42,6 +44,11 @@ def fast_inverse_sqrt(number: float) -> float:
4244

4345

4446
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
4652

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

Comments
 (0)