Added Fast Inverse Square Root (#11054)

* Feat: Added Fast inverse square root

* Fix: Added typehint

* Fix: Added doctests that break the code, changed var name

* updating DIRECTORY.md

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix: fixed length of docstring

* Update fast_inverse_sqrt.py

---------

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Aryansh B 2023-10-30 02:27:37 +05:30 committed by GitHub
parent eafdb8b866
commit 760d9bedc1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 64 additions and 0 deletions

View File

@ -34,6 +34,7 @@
* [Bitwise Addition Recursive](bit_manipulation/bitwise_addition_recursive.py) * [Bitwise Addition Recursive](bit_manipulation/bitwise_addition_recursive.py)
* [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
* [Excess 3 Code](bit_manipulation/excess_3_code.py)
* [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py)
* [Highest Set Bit](bit_manipulation/highest_set_bit.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py)
* [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py) * [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py)
@ -170,7 +171,10 @@
* Arrays * Arrays
* [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py) * [Equilibrium Index In Array](data_structures/arrays/equilibrium_index_in_array.py)
* [Find Triplets With 0 Sum](data_structures/arrays/find_triplets_with_0_sum.py) * [Find Triplets With 0 Sum](data_structures/arrays/find_triplets_with_0_sum.py)
* [Index 2D Array In 1D](data_structures/arrays/index_2d_array_in_1d.py)
* [Kth Largest Element](data_structures/arrays/kth_largest_element.py)
* [Median Two Array](data_structures/arrays/median_two_array.py) * [Median Two Array](data_structures/arrays/median_two_array.py)
* [Monotonic Array](data_structures/arrays/monotonic_array.py)
* [Pairs With Given Sum](data_structures/arrays/pairs_with_given_sum.py) * [Pairs With Given Sum](data_structures/arrays/pairs_with_given_sum.py)
* [Permutations](data_structures/arrays/permutations.py) * [Permutations](data_structures/arrays/permutations.py)
* [Prefix Sum](data_structures/arrays/prefix_sum.py) * [Prefix Sum](data_structures/arrays/prefix_sum.py)
@ -368,6 +372,7 @@
## Electronics ## Electronics
* [Apparent Power](electronics/apparent_power.py) * [Apparent Power](electronics/apparent_power.py)
* [Builtin Voltage](electronics/builtin_voltage.py) * [Builtin Voltage](electronics/builtin_voltage.py)
* [Capacitor Equivalence](electronics/capacitor_equivalence.py)
* [Carrier Concentration](electronics/carrier_concentration.py) * [Carrier Concentration](electronics/carrier_concentration.py)
* [Charging Capacitor](electronics/charging_capacitor.py) * [Charging Capacitor](electronics/charging_capacitor.py)
* [Charging Inductor](electronics/charging_inductor.py) * [Charging Inductor](electronics/charging_inductor.py)
@ -531,12 +536,14 @@
## Machine Learning ## Machine Learning
* [Apriori Algorithm](machine_learning/apriori_algorithm.py) * [Apriori Algorithm](machine_learning/apriori_algorithm.py)
* [Astar](machine_learning/astar.py) * [Astar](machine_learning/astar.py)
* [Automatic Differentiation](machine_learning/automatic_differentiation.py)
* [Data Transformations](machine_learning/data_transformations.py) * [Data Transformations](machine_learning/data_transformations.py)
* [Decision Tree](machine_learning/decision_tree.py) * [Decision Tree](machine_learning/decision_tree.py)
* [Dimensionality Reduction](machine_learning/dimensionality_reduction.py) * [Dimensionality Reduction](machine_learning/dimensionality_reduction.py)
* Forecasting * Forecasting
* [Run](machine_learning/forecasting/run.py) * [Run](machine_learning/forecasting/run.py)
* [Frequent Pattern Growth](machine_learning/frequent_pattern_growth.py) * [Frequent Pattern Growth](machine_learning/frequent_pattern_growth.py)
* [Gradient Boosting Classifier](machine_learning/gradient_boosting_classifier.py)
* [Gradient Descent](machine_learning/gradient_descent.py) * [Gradient Descent](machine_learning/gradient_descent.py)
* [K Means Clust](machine_learning/k_means_clust.py) * [K Means Clust](machine_learning/k_means_clust.py)
* [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py)
@ -598,6 +605,7 @@
* [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py)
* [Factorial](maths/factorial.py) * [Factorial](maths/factorial.py)
* [Factors](maths/factors.py) * [Factors](maths/factors.py)
* [Fast Inverse Sqrt](maths/fast_inverse_sqrt.py)
* [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py)
* [Fibonacci](maths/fibonacci.py) * [Fibonacci](maths/fibonacci.py)
* [Find Max](maths/find_max.py) * [Find Max](maths/find_max.py)
@ -648,6 +656,7 @@
* [Numerical Integration](maths/numerical_analysis/numerical_integration.py) * [Numerical Integration](maths/numerical_analysis/numerical_integration.py)
* [Runge Kutta](maths/numerical_analysis/runge_kutta.py) * [Runge Kutta](maths/numerical_analysis/runge_kutta.py)
* [Runge Kutta Fehlberg 45](maths/numerical_analysis/runge_kutta_fehlberg_45.py) * [Runge Kutta Fehlberg 45](maths/numerical_analysis/runge_kutta_fehlberg_45.py)
* [Runge Kutta Gills](maths/numerical_analysis/runge_kutta_gills.py)
* [Secant Method](maths/numerical_analysis/secant_method.py) * [Secant Method](maths/numerical_analysis/secant_method.py)
* [Simpson Rule](maths/numerical_analysis/simpson_rule.py) * [Simpson Rule](maths/numerical_analysis/simpson_rule.py)
* [Square Root](maths/numerical_analysis/square_root.py) * [Square Root](maths/numerical_analysis/square_root.py)
@ -814,6 +823,7 @@
* [Ideal Gas Law](physics/ideal_gas_law.py) * [Ideal Gas Law](physics/ideal_gas_law.py)
* [In Static Equilibrium](physics/in_static_equilibrium.py) * [In Static Equilibrium](physics/in_static_equilibrium.py)
* [Kinetic Energy](physics/kinetic_energy.py) * [Kinetic Energy](physics/kinetic_energy.py)
* [Lens Formulae](physics/lens_formulae.py)
* [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py)
* [Malus Law](physics/malus_law.py) * [Malus Law](physics/malus_law.py)
* [Mass Energy Equivalence](physics/mass_energy_equivalence.py) * [Mass Energy Equivalence](physics/mass_energy_equivalence.py)

View File

@ -0,0 +1,54 @@
"""
Fast inverse square root (1/sqrt(x)) using the Quake III algorithm.
Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root
Accuracy: https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy
"""
import struct
def fast_inverse_sqrt(number: float) -> float:
"""
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_inverse_sqrt(10)
0.3156857923527257
>>> fast_inverse_sqrt(4)
0.49915357479239103
>>> fast_inverse_sqrt(4.1)
0.4932849504615651
>>> fast_inverse_sqrt(0)
Traceback (most recent call last):
...
ValueError: Input must be a positive number.
>>> fast_inverse_sqrt(-1)
Traceback (most recent call last):
...
ValueError: Input must be a positive number.
>>> from math import isclose, sqrt
>>> all(isclose(fast_inverse_sqrt(i), 1 / sqrt(i), rel_tol=0.00132)
... for i in range(50, 60))
True
"""
if number <= 0:
raise ValueError("Input must be a positive number.")
i = struct.unpack(">i", struct.pack(">f", number))[0]
i = 0x5F3759DF - (i >> 1)
y = struct.unpack(">f", struct.pack(">i", i))[0]
return y * (1.5 - 0.5 * number * y * y)
if __name__ == "__main__":
from doctest import testmod
testmod()
# https://en.wikipedia.org/wiki/Fast_inverse_square_root#Accuracy
from math import sqrt
for i in range(5, 101, 5):
print(f"{i:>3}: {(1 / sqrt(i)) - fast_inverse_sqrt(i):.5f}")