Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Project1: a better way to perform ceiled division #33

Closed
Pokryton opened this issue Sep 11, 2024 · 1 comment · Fixed by #40
Closed

Project1: a better way to perform ceiled division #33

Pokryton opened this issue Sep 11, 2024 · 1 comment · Fixed by #40
Assignees

Comments

@Pokryton
Copy link

In Project 1 of this book, when calculating the size of an encoded or decoded string, ceiled division of usize is done by casting to f64 and calling the @ceil function.

The `_calc_encode_length()` function below encapsulates this logic. Notice that we convert
the `.len` property of the array, which is always a integer (more precisely, an `usize` value),
into a floating point number of 64 bits (`f64`). We do this, because the ceiling function (`@ceil()`) works
only with floating point numbers. So, we convert it so that the division with the number `3.0` results in
a floating point number. Then, after the ceiling process, we can convert the result back into an
integer value (with the `@intFromFloat()` function).
```{zig}
#| auto_main: false
#| build_type: "lib"
fn _calc_encode_length(input: []const u8) u64 {
if (input.len < 3) {
const n_output: u64 = 4;
return n_output;
}
const len_as_float: f64 = @floatFromInt(input.len);
const n_output: u64 = @intFromFloat(@ceil(len_as_float / 3.0) * 4.0);
return n_output;
}
```

While this approach works, it may lost precision in extreme cases (unlikely though), and floating point arithmetic is generally much more expensive than integer arithmetic. A better approach would be to use std.math.divCeil(usize, input.len, 3) or simply (input.len + 2) / 3. This is also easier to read IMO.

For reference, here's how the same functionality implemented in the standard library.

https://github.com/ziglang/zig/blob/218cf059dd215282aa96d6b4715e68d533a4238e/lib/std/base64.zig#L93-L100

@pedropark99
Copy link
Owner

Hey @Pokryton ! First of all, thank you for your comment!
It is a good suggestion. I will make it happen 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants