Get a pseudorandom f64 from another f64

Hi. I need a hash function that takes a f64 and returns a f64 between 0 and 1.

I’ve found that std.hash.intis almost what I need, but I’m missing one piece of the puzzle: How do I cast a f64 to a u64?

const std = @import("std");

pub fn main() void {
    const prev: u64 = 2; // works with u64 input
    const n: f64 = @floatFromInt(std.hash.int(prev));
    const max: f64 = @floatFromInt(std.math.maxInt(u64));
    const next: f64 = n / max;
    std.debug.print("{any} {any}\n", .{ prev, next });
}

@intFromFloatwill drop the floating part, so it won’t do what I want. I guess I want my program to look at those 8 bytes and read it as if it was a u64

1 Like

If you really don’t care about the semantic meaning you can use const i: u64 = @bitCast(f);.

4 Likes

thanks a lot!