Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Computing Ceil of Log2 in Rust

I want to calculate the following in Rust:

Python Equivalent:

math.ceil(math.log(b+1, 2))

ceil(log_2 n+1)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried:

a+1.log2() 
(a+1).log2() 

but I get the error use of unstable library feature 'int_log'. I don’t want to use an unstable library feature. What is the easiest way to calculate log2, without any external crates if possible?

>Solution :

Rust is very particular about the difference between ints and floats. You can’t just type a integer and expect it to be auto-casted automatically. Always add a . at the end for a float.

Seems like you attempted to call the function on a integer. Try this:

Try this:

(1.).log2().ceil()

or

(a as f32 + 1.).log2().ceil()

If you want the end result as a integer you can use as i32 at the end. If you want double precision floats replace f32 with f64.

Reference:

https://doc.rust-lang.org/std/primitive.f32.html#method.ceil

https://doc.rust-lang.org/std/primitive.f32.html#method.log2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading