Comparison of two floats in Rust with an arbitrary level of accuracy

How can I do a comparison at an arbitrary level of accuracy so that I can see that the two numbers are the same? In Python, I would use a type function round(), so I'm looking for something equivalent in Rust.

For example, I have:

let x = 1.45555454;
let y = 1.45556766;

In my case, they look like 2 decimal places. Thus, xthey ywill become 1.46 for comparison. I could format them, but it is certainly slow, which is the best Rust method for checking equivalence, therefore:

if x == y { // called when we match to 2 decimal places}

To further clarify the problem and give some context. This is valid for the accuracy of dollars and cents. Therefore python, a function round()with all its problems will usually be used . Yes, I know the limitations of the floating point representation. There are two functions that calculate the amount, I calculate in dollars and must process part of the cents to the nearest penny.

The reason to ask the community is that I suspect that if I give up my own, it may affect performance, and this aspect is why I use Rust, so I'm here. Plus, I saw something called round () in the Rust documentation, but it seems to use null parameters, unlike the pythons version.

+4
1

Python:

. round() : , round(2.675, 2) 2.67 2.68. : , float.

.


, , . , :

fn approx_equal(a: f64, b: f64, decimal_places: u8) -> bool {
    let factor = 10.0f64.powi(decimal_places as i32);
    let a = (a * factor).trunc();
    let b = (b * factor).trunc();
    a == b
}

fn main() {
    assert!( approx_equal(1.234, 1.235, 1));
    assert!( approx_equal(1.234, 1.235, 2));
    assert!(!approx_equal(1.234, 1.235, 3));
}

A , (, ,), :

  • /
  • NaN
  • (approx_equal(0.09, -0.09, 1))

- , , .

+5

Source: https://habr.com/ru/post/1665642/


All Articles