6
6
import struct
7
7
8
8
9
- def fastInvSqrt ( x : float ) -> float :
9
+ def fast_inverse_sqrt ( number : float ) -> float :
10
10
"""
11
11
Calculate the fast inverse square root of a number.
12
12
13
13
This function computes the fast inverse square root of a floating-point number
14
14
using the famous Quake III algorithm, originally developed by id Software.
15
15
16
- :param float x : The input number for which to calculate the inverse square root.
16
+ :param float number : The input number for which to calculate the inverse square root.
17
17
:return float: The fast inverse square root of the input number.
18
18
19
19
Example:
20
- >>> fastInvSqrt (10)
20
+ >>> fast_inverse_sqrt (10)
21
21
0.3156857923527257
22
22
23
- >>> fastInvSqrt (4)
23
+ >>> fast_inverse_sqrt (4)
24
24
0.49915357479239103
25
+
26
+ >>> fast_inverse_sqrt(0)
27
+ Traceback (most recent call last):
28
+ ...
29
+ ValueError: Input must be a positive number.
30
+
31
+ >>> fast_inverse_sqrt(-1)
32
+ Traceback (most recent call last):
33
+ ...
34
+ ValueError: Input must be a positive number.
25
35
"""
26
- i = struct .unpack ('>i' , struct .pack ('>f' , x ))[0 ]
36
+ if number <= 0 :
37
+ raise ValueError ("Input must be a positive number." )
38
+ i = struct .unpack ('>i' , struct .pack ('>f' , number ))[0 ]
27
39
i = 0x5f3759df - (i >> 1 )
28
40
y = struct .unpack ('>f' , struct .pack ('>i' , i ))[0 ]
29
- return y * (1.5 - 0.5 * x * y * y )
41
+ return y * (1.5 - 0.5 * number * y * y )
30
42
31
43
if __name__ == "__main__" :
32
44
import doctest
33
45
34
- doctest .testmod (verbose = True )
46
+ doctest .testmod (verbose = True )
0 commit comments