How to deal with floating point arithmetic in Rust?
fn main() {
let vector = vec![1.01_f64, 1.02, 1.03, 1.01, 1.05];
let difference: Vec<f64> = vector.windows(2).map(|slice| slice[0] - slice[1]).collect();
println!("{:?}", difference);
}
Returns:
[-0.010000000000000009, -0.010000000000000009, 0.020000000000000018, -0.040000000000000036]
Expected output:
[-0.01, -0.01, 0.02, -0.04]
I understand the reason for this happening but have never had to address it.
Update:
This post came about because results in other languages such as Python appeared to be exact. The plan was to replicate Python's approach in Rust however upon further investigation, Python, numpy and pandas all deal with numbers in the same way. That is, the inaccuracies are still present however not always visible/shown. Rust on the other hand made these innacuracies obvious which was confusing at first.
Example:
l = [1.01, 1.02, 1.03, 1.01, 1.05]
for i in l:
print('%.18f' % i)
Prints:
1.010000000000000009
1.020000000000000018
1.030000000000000027
1.010000000000000009
1.050000000000000044
whereas print(l)
prints:
[1.01, 1.02, 1.03, 1.01, 1.05]
-0.010000000000000009
is 17 significant digits. – Accordance