Created
January 6, 2021 00:08
-
-
Save pedrocr/81706cc9d49be183dc339bfe278c802a to your computer and use it in GitHub Desktop.
Precision of FastInvSquare
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
fn fast_invsqrt(number: f32, iterations: usize) -> f32 { | |
let threehalfs: f32 = 1.5; | |
let x2: f32 = number * 0.5; | |
let mut i: u32 = number.to_bits(); | |
i = 0x5f3759df - (i >> 1); | |
let mut y: f32 = f32::from_bits(i); | |
for _ in 0..iterations { | |
y = y * ( threehalfs - ( x2 * y * y ) ); | |
} | |
y | |
} | |
fn slow_invsqrt(number: f32) -> f32 { | |
1.0 / number.sqrt() | |
} | |
const MAX_ROUNDS: usize = 3; | |
fn main() { | |
let mut maxdeltas = [0f32; MAX_ROUNDS+1]; | |
for i in 0..u32::MAX { | |
let number = f32::from_bits(i); | |
if number.is_normal() { | |
let slow = slow_invsqrt(number); | |
for i in 0..MAX_ROUNDS+1 { | |
let fast = fast_invsqrt(number, i); | |
let delta = ((fast / slow) - 1.0).abs(); | |
if delta > maxdeltas[i] { | |
maxdeltas[i] = delta; | |
} | |
} | |
} | |
} | |
for i in 0..MAX_ROUNDS+1 { | |
println!("Maximum innacuracy {} rounds: {:#?}%", i, maxdeltas[i] * 100.0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment