#Comparing a int with an int that is multiplied by a float

1 messages · Page 1 of 1 (latest)

clear blaze
#

I need to do something along the lines of

if (self.count + 1 > self.entries.len * max_load) {
  ,,,

where max_load is an f64 set to 0.75 and both .len and .count are usize

obviously zig requires you to convert them to proper values, but in the above example i will have to

  1. convert self.entries.len to float
  2. multiply it by max_load
  3. convert it back to usize
  4. THEN do the comparison

with all of the above it now looks like

if (self.count + 1 > @as(usize, @intFromFloat(@as(f64, @floatFromInt(self.entries.len)) * max_load))) {
  ...

this works but is insanely ugly, is there a better way to do it?

fresh beacon
#

It's ugly because it's accurately describing the steps the code actually has to perform to calculate the result, unlike other languages which might silently convert to and from floats/ints of different sizes

#

It might read better if you break it down into intermediate variables, e.g.

const len_f64: f64 = @floatFromInt(self.entries.len);
const threshold: usize = @intFromFloat(len_f64 * max_load);
if (self.count + 1 > threshold) {
    //
}
clear blaze
#

hmm, i guess there's no other way then