-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
Summary
approx_constant could cover cases where an imprecise decimal approximation to a low-denominator fraction is being used, such as 0.33333
, 0.667
, 3.8333333
or perhaps 0.142857
.
Since 1.82, these can be written in constants as 1.0 / 3.0
, 2.0 / 3.0
, 23.0 / 6.0
and 1.0 / 7.0
, respectively.
I'm not sure what the right threshold is. If someone writes 0.01030927835
, then the chances 1.0 / 97.0
is not an improvement are pretty slim. On the other hand, every decimal expansion approximates some rational.
The ideal solution might be:
- Convert the fractional part of the constant to a continued fraction.
- Find the first rational approximations that match all the digits given, by truncation and rounding, as Clippy does at the moment. This may give two – check both.
- Check that the continued fraction doesn't terminate here (making the constant exactly correct) and that the next coefficient is above some threshold (which may increase with depth into the fraction, perhaps 100 × depth or something like that).
If that's too slow or complicated, then just special-casing thirds, sixes, sevenths and nineths probably gets 90 % of the benefit.
Lint Name
approx_constant
Reproducer
I tried this code:
const ONE_THIRD: f64 = 0.33333;
I expected to see this happen:
approximate value of
1 / 3
found.
Instead, this happened:
[no error]
Version
rustc 1.90.0-nightly (2a023bf80 2025-07-10)
binary: rustc
commit-hash: 2a023bf80a6fbd6a06d5460a34eb247b986286ed
commit-date: 2025-07-10
host: x86_64-unknown-linux-gnu
release: 1.90.0-nightly
LLVM version: 20.1.7