#Zig Newbie Numbers Arithmetic

1 messages · Page 1 of 1 (latest)

errant grotto
#

I wonder if there's a way to to the same mathematical operations without having to do a lot of casts, and by casts I'm including creating another variable to hold the same value but with another type too. I think there's just too many casts for a simple operation like this.

This is the zig code: const pixel: u32 = @as(u32, @intFromFloat((@as(f32, @floatFromInt(x)) / @as(f32, @floatFromInt(window.width))) * 255.0)) % 256

The equivalent in C would be: (unsigned) ((float) x / window.width * 255.0f) % 256

compact gazelle
#

its the same number of casts in c, c just does more implicitly.
the only way around it is to change the types earlier, perhaps from the begining.
but that might introduce more casts in other places.
try it out and pick whatever you like the most.

zig does plan to address this eventually, its just not a priority at the moment.
but it will never do as much implicitly as c.

errant grotto
desert swan
radiant crane
#

...or you could just make fn as_f32(x: anytype) f32 { return @floatFromInt(x); } instead of taking on a whole dependency

desert swan
#

That's literally just rewriting the dependency yourself though :P

#

You don't have to add the whole library. I think this should just be the relevant part

sullen dirge
#

or split your expressions over multiple const assignments. That way you can avoid nested @as builtins.

in fact if you see many nested as builtins, that means it's time to split it up

#

from your example:

const x_f: f32 = @floatFromInt(x);
const width_f = @floatFromInt(width);
const pixel_unclamped: u32 = @intFromFloat(x_f / width_ f * 255.0);
const pixel: u8 = @intCast(pixel_unclamped % 256);

in zig you embrace that you're doing computing with concrete machine with concrete datatypes.