]> git.lizzy.rs Git - rust.git/blob - src/docs/float_cmp_const.txt
Auto merge of #9421 - xphoniex:fix-#9420, r=giraffate
[rust.git] / src / docs / float_cmp_const.txt
1 ### What it does
2 Checks for (in-)equality comparisons on floating-point
3 value and constant, except in functions called `*eq*` (which probably
4 implement equality for a type involving floats).
5
6 ### Why is this bad?
7 Floating point calculations are usually imprecise, so
8 asking if two values are *exactly* equal is asking for trouble. For a good
9 guide on what to do, see [the floating point
10 guide](http://www.floating-point-gui.de/errors/comparison).
11
12 ### Example
13 ```
14 let x: f64 = 1.0;
15 const ONE: f64 = 1.00;
16
17 if x == ONE { } // where both are floats
18 ```
19
20 Use instead:
21 ```
22 let error_margin = f64::EPSILON; // Use an epsilon for comparison
23 // Or, if Rust <= 1.42, use `std::f64::EPSILON` constant instead.
24 // let error_margin = std::f64::EPSILON;
25 if (x - ONE).abs() < error_margin { }
26 ```