mirror of
https://github.com/rust-lang/rust.git
synced 2024-11-24 07:44:10 +00:00
9bbc470e97
Add Integer::log variants _This is another attempt at landing https://github.com/rust-lang/rust/pull/70835, which was approved by the libs team but failed on Android tests through Bors. The text copied here is from the original issue. The only change made so far is the addition of non-`checked_` variants of the log methods._ _Tracking issue: #70887_ --- This implements `{log,log2,log10}` methods for all integer types. The implementation was provided by `@substack` for use in the stdlib. _Note: I'm not big on math, so this PR is a best effort written with limited knowledge. It's likely I'll be getting things wrong, but happy to learn and correct. Please bare with me._ ## Motivation Calculating the logarithm of a number is a generally useful operation. Currently the stdlib only provides implementations for floats, which means that if we want to calculate the logarithm for an integer we have to cast it to a float and then back to an int. > would be nice if there was an integer log2 instead of having to either use the f32 version or leading_zeros() which i have to verify the results of every time to be sure _— [`@substack,` 2020-03-08](https://twitter.com/substack/status/1236445105197727744)_ At higher numbers converting from an integer to a float we also risk overflows. This means that Rust currently only provides log operations for a limited set of integers. The process of doing log operations by converting between floats and integers is also prone to rounding errors. In the following example we're trying to calculate `base10` for an integer. We might try and calculate the `base2` for the values, and attempt [a base swap](https://www.rapidtables.com/math/algebra/Logarithm.html#log-rules) to arrive at `base10`. However because we're performing intermediate rounding we arrive at the wrong result: ```rust // log10(900) = ~2.95 = 2 dbg!(900f32.log10() as u64); // log base change rule: logb(x) = logc(x) / logc(b) // log2(900) / log2(10) = 9/3 = 3 dbg!((900f32.log2() as u64) / (10f32.log2() as u64)); ``` _[playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bd6c68b3539e400f9ca4fdc6fc2eed0)_ This is somewhat nuanced as a lot of the time it'll work well, but in real world code this could lead to some hard to track bugs. By providing correct log implementations directly on integers we can help prevent errors around this. ## Implementation notes I checked whether LLVM intrinsics existed before implementing this, and none exist yet. ~~Also I couldn't really find a better way to write the `ilog` function. One option would be to make it a private method on the number, but I didn't see any precedent for that. I also didn't know where to best place the tests, so I added them to the bottom of the file. Even though they might seem like quite a lot they take no time to execute.~~ ## References - [Log rules](https://www.rapidtables.com/math/algebra/Logarithm.html#log-rules) - [Rounding error playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6bd6c68b3539e400f9ca4fdc6fc2eed0) - [substack's tweet asking about integer log2 in the stdlib](https://twitter.com/substack/status/1236445105197727744) - [Integer Logarithm, A. Jaffer 2008](https://people.csail.mit.edu/jaffer/III/ilog.pdf)
108 lines
2.4 KiB
Rust
108 lines
2.4 KiB
Rust
#![feature(alloc_layout_extra)]
|
|
#![feature(array_chunks)]
|
|
#![feature(array_methods)]
|
|
#![feature(array_map)]
|
|
#![feature(array_windows)]
|
|
#![feature(bool_to_option)]
|
|
#![feature(box_syntax)]
|
|
#![feature(cell_update)]
|
|
#![feature(cfg_panic)]
|
|
#![feature(cfg_target_has_atomic)]
|
|
#![feature(const_assume)]
|
|
#![feature(const_cell_into_inner)]
|
|
#![feature(const_maybe_uninit_assume_init)]
|
|
#![feature(const_ptr_read)]
|
|
#![feature(const_ptr_write)]
|
|
#![feature(const_ptr_offset)]
|
|
#![feature(core_intrinsics)]
|
|
#![feature(core_private_bignum)]
|
|
#![feature(core_private_diy_float)]
|
|
#![feature(dec2flt)]
|
|
#![feature(div_duration)]
|
|
#![feature(duration_consts_2)]
|
|
#![feature(duration_constants)]
|
|
#![feature(exact_size_is_empty)]
|
|
#![feature(extern_types)]
|
|
#![feature(flt2dec)]
|
|
#![feature(fmt_internals)]
|
|
#![feature(hashmap_internals)]
|
|
#![feature(try_find)]
|
|
#![feature(is_sorted)]
|
|
#![feature(pattern)]
|
|
#![feature(sort_internals)]
|
|
#![feature(slice_partition_at_index)]
|
|
#![feature(maybe_uninit_uninit_array)]
|
|
#![feature(maybe_uninit_array_assume_init)]
|
|
#![feature(maybe_uninit_extra)]
|
|
#![feature(maybe_uninit_write_slice)]
|
|
#![feature(min_specialization)]
|
|
#![feature(numfmt)]
|
|
#![feature(step_trait)]
|
|
#![feature(str_internals)]
|
|
#![feature(test)]
|
|
#![feature(trusted_len)]
|
|
#![feature(try_trait_v2)]
|
|
#![feature(slice_internals)]
|
|
#![feature(slice_partition_dedup)]
|
|
#![feature(int_log)]
|
|
#![feature(iter_advance_by)]
|
|
#![feature(iter_partition_in_place)]
|
|
#![feature(iter_intersperse)]
|
|
#![feature(iter_is_partitioned)]
|
|
#![feature(iter_order_by)]
|
|
#![feature(iter_map_while)]
|
|
#![feature(const_mut_refs)]
|
|
#![feature(const_pin)]
|
|
#![feature(const_slice_from_raw_parts)]
|
|
#![feature(const_raw_ptr_deref)]
|
|
#![feature(never_type)]
|
|
#![feature(unwrap_infallible)]
|
|
#![feature(option_result_unwrap_unchecked)]
|
|
#![feature(result_into_ok_or_err)]
|
|
#![feature(ptr_metadata)]
|
|
#![feature(once_cell)]
|
|
#![feature(unsized_tuple_coercion)]
|
|
#![feature(const_option)]
|
|
#![feature(integer_atomics)]
|
|
#![feature(slice_group_by)]
|
|
#![feature(trusted_random_access)]
|
|
#![feature(unsize)]
|
|
#![deny(unsafe_op_in_unsafe_fn)]
|
|
|
|
extern crate test;
|
|
|
|
mod alloc;
|
|
mod any;
|
|
mod array;
|
|
mod ascii;
|
|
mod atomic;
|
|
mod bool;
|
|
mod cell;
|
|
mod char;
|
|
mod clone;
|
|
mod cmp;
|
|
mod const_ptr;
|
|
mod fmt;
|
|
mod hash;
|
|
mod intrinsics;
|
|
mod iter;
|
|
mod lazy;
|
|
mod macros;
|
|
mod manually_drop;
|
|
mod mem;
|
|
mod nonzero;
|
|
mod num;
|
|
mod ops;
|
|
mod option;
|
|
mod pattern;
|
|
mod pin;
|
|
mod ptr;
|
|
mod result;
|
|
mod slice;
|
|
mod str;
|
|
mod str_lossy;
|
|
mod task;
|
|
mod time;
|
|
mod tuple;
|
|
mod unicode;
|