RU beehive logo promo banner for Computing & Info Sciences
CS 320
2025spring
ibarland

Unit Testing Floating-point
in Rust

Floating-point numbers are approximations

Is \(\frac{x}{25} \cdot 25\) equal to \(x\)? Of course it is! Unless you are using floating-point arithmetic. (Try it \(x=7\), then \(14\), then \(21\).)

We understand the reason: Floating point arithmetic uses a fixed number of digits to represent numbers, though the location of the decimal-point might float1. And if you have a number like ⅓, but only use (say) 17 digits, you can't represent that perfectly (in base-10); you're left with a number that is very very3 close to the number you really want — but not == to it!

When modeling using doubles (or f64s or f32s or floats etc.), keep these facts in mind:

This last point bears repeating: Do not compare doubles with ==! But then, how do we compare two floating-point numbers? There are several approaches, each with their own drawbacks:

Rust: How to install & use the assert_float_eq crate

In order to use unit tests with assert_f46_near, you first need to install the external crate (library) assert_float_eq. It's easy to do this, in either of two ways:

At this point, you can call the function via its full-name, assert_float_eq::assert_f64_near(,). However, that's quite a mouthful! Instead, you can write a line at the top of your file: use assert_float_eq::assert_f64_near;. At this point, you can just use that function's first name, assert_f64_near(,).


1 So floating-point numbers with 3 (decimal) digits of accuracy can represent each of 3.14 and 31,400 and 0.00314, so long as we track the location of the decimal-point separately, which is what floating-point numbers do      
3 Pluto is part of the solar system, dangit!      
2 If the solar system3 is 7 barlands long, then 7.000000000000001 barlands is only one millimeter bigger. That is crazy close to the same thing.      

logo for creative commons by-attribution license
This page licensed CC-BY 4.0 Ian Barland
Page last generated
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Rendered by Racket.