MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / fast_inverse_sqrt

Function fast_inverse_sqrt

maths/fast_inverse_sqrt.py:10–43  ·  view source on GitHub ↗

Compute the fast inverse square root of a floating-point number using the famous Quake III algorithm. :param float number: Input number for which to calculate the inverse square root. :return float: The fast inverse square root of the input number. Example: >>> fast_invers

(number: float)

Source from the content-addressed store, hash-verified

8
9
10def fast_inverse_sqrt(number: float) -> float:
11 """
12 Compute the fast inverse square root of a floating-point number using the famous
13 Quake III algorithm.
14
15 :param float number: Input number for which to calculate the inverse square root.
16 :return float: The fast inverse square root of the input number.
17
18 Example:
19 >>> fast_inverse_sqrt(10)
20 0.3156857923527257
21 >>> fast_inverse_sqrt(4)
22 0.49915357479239103
23 >>> fast_inverse_sqrt(4.1)
24 0.4932849504615651
25 >>> fast_inverse_sqrt(0)
26 Traceback (most recent call last):
27 ...
28 ValueError: Input must be a positive number.
29 >>> fast_inverse_sqrt(-1)
30 Traceback (most recent call last):
31 ...
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
37 """
38 if number <= 0:
39 raise ValueError("Input must be a positive number.")
40 i = struct.unpack(">i", struct.pack(">f", number))[0]
41 i = 0x5F3759DF - (i >> 1)
42 y = struct.unpack(">f", struct.pack(">i", i))[0]
43 return y * (1.5 - 0.5 * number * y * y)
44
45
46if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected