Created
February 25, 2022 04:28
-
-
Save SleepingInsomniac/6da06f0ee14bcb32a4b8614475d50c52 to your computer and use it in GitHub Desktop.
Fast Inverse Square Root
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "benchmark" | |
| n = 100.0 | |
| # From Quake 3 arena | |
| def fast_inverse_sqrt(num : Float32) | |
| i = uninitialized Int64 | |
| x2 = uninitialized Float32 | |
| y = uninitialized Float32 | |
| x2 = (num * 0.5).to_f32 | |
| y = num | |
| i = pointerof(y).as(Int64*).value | |
| i = 0x5F3759DF_i64 - (i >> 1) | |
| y = pointerof(i).as(Float32*).value | |
| y = y * (1.5 - (x2 * y * y)) | |
| # y = y * (1.5 - (x2 * y * y)) # 2nd iteration | |
| # y = y * (1.5 - (x2 * y * y)) # 3rd iteration | |
| end | |
| Benchmark.ips do |x| | |
| x.report("inverse math square root") do | |
| 1 / Math.sqrt(n) | |
| end | |
| x.report("fast inverse square root") do | |
| fast_inverse_sqrt(n.to_f32) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment