rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.84k stars 354 forks source link

Floating Point Related Idioms #325

Open louy2 opened 1 year ago

louy2 commented 1 year ago

Floating point numbers are known to be an imperfect model of real numbers, causing rounding errors in calculations and difficulty for equality comparison.

For example, the Euclidean length example in the Interpreter chapter using sqrt has an average error of 2.9 bits for 4-dimension and 13.9 bits for 2-dimension, with more and bigger errors (over 56-bit errors) happening at points very close to the axes. This can be improved by using hypot ("hypotenus") instead. (Herbie page for 4D Euclid length) (Herbie page for 2D Euclid length)

Similarly, taking the angle between two 2-dimentional vectors has an average error of 34.3 bits, again with more and bigger errors (64-bit errors) closer to the axes, can be improved with hypot and mul_add (aka fma, "fused multiply add") to cut the average error down to 18.9 bits. (Herbie page for angle between vectors)

(The error figures above are taken from the results of Herbie project.)

A related problem is that nominally equal floating point expressions often do not compare equal due to rounding errors. This necessitates something like the crate float-cmp.

These are not Rust specific idioms per se, but I feel like this is a good place to raise awareness of these errors and list Rust specific solutions.

simonsan commented 1 year ago

These are not Rust specific idioms per se, but I feel like this is a good place to raise awareness of these errors and list Rust specific solutions.

Agreed. Though the focus of the interpreter article is not really on that, I would agree that it would be worth to have a new article about the topic within idioms.

Would you be willing to write that? You seem to be deep in the topic here?