Skip to content

Instantly share code, notes, and snippets.

@gain620
Created February 21, 2025 09:45
Show Gist options
  • Select an option

  • Save gain620/5e71d6db876135ca77d4058a2bcc048f to your computer and use it in GitHub Desktop.

Select an option

Save gain620/5e71d6db876135ca77d4058a2bcc048f to your computer and use it in GitHub Desktop.
Fast Inverse Square Root for Zig
const std = @import("std");
/// Compute the fast inverse square root of a given f32 number.
pub fn fastInvSqrt(number: f32) f32 {
// Interpret the floating-point number as an unsigned 32-bit integer.
var i: u32 = @bitCast(u32, number);
// Magic constant and bit manipulation.
i = 0x5f3759df - (i >> 1);
// Reinterpret the bits back into a floating-point value.
var y: f32 = @bitCast(f32, i);
// One iteration of Newton's method to improve the approximation.
y = y * (1.5 - (number * 0.5 * y * y));
return y;
}
pub fn main() !void {
var stdout = std.io.getStdOut().writer();
const number: f32 = 4.0;
const invSqrt = fastInvSqrt(number);
try stdout.print("Fast Inverse Square Root of {} is {}\n", .{number, invSqrt});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment