Asserting Values in Range
Understand the challenges of floating-point precision in unit testing and learn how to assert floating-point values within a tolerance using NUnit. This lesson explains floating-point imprecision, potential rounding errors, and demonstrates how to apply NUnit assertions with fixed, percent, or ulp tolerance to ensure reliable test results when working with real number approximations.
We'll cover the following...
Introduction
With the advent of digital computation, one of the first applications of programs was to solve problems within the scientific computing field. Scientific computing focuses on operations with real numbers. Unfortunately, perfectly representing any arbitrary real number within a machine architecture is impossible. As a result, numerous real number representation schemes have been proposed and implemented to ensure such representations are as accurate as possible.
Floating-point numbers are a data type that represents real numbers in machine architecture. Understanding the detailed mechanics of floating-point numbers is not necessary for unit testing. However, it is vital to understand the potential pitfalls when dealing with floating-point numbers, so that when one of our floating-point assertions doesn’t pass, we will know how to correct it.
The non-precise nature of floating-point types
The floating-point numeric types all represent real numbers. Real numbers are those that assume any value along a continuous number line. Real numbers can equal a value from negative to positive infinity and may equal an infinitely small or large ...