Skip to main content

approximately_equal

Function approximately_equal 

Source
pub fn approximately_equal<T: RealScalar>(
    a: T,
    b: T,
    tolerance: &AbsoluteTolerance<T>,
) -> bool
Expand description

Compares two scalar values within an absolute tolerance.

Tests whether the absolute difference between two values is less than or equal to a specified tolerance. This is the standard approach for approximate floating-point comparisons when the expected magnitude of values is known.

§Mathematical Definition

Returns true if and only if:

|a - b| ≤ tolerance

§Symmetry

The comparison is symmetric: approximately_equal(a, b, tol) == approximately_equal(b, a, tol)

§Type Parameters

§Arguments

  • a: First value
  • b: Second value to compare with
  • tolerance: The maximum allowed absolute difference (must be non-negative)

§Examples

§Basic Floating-Point Comparison

use num_valid::scalars::{AbsoluteTolerance, approximately_equal};
use try_create::TryNew;

let tol = AbsoluteTolerance::try_new(1e-10_f64).unwrap();

// Values within tolerance
assert!(approximately_equal(1.0, 1.0 + 1e-11, &tol));

// Values outside tolerance
assert!(!approximately_equal(1.0, 1.0 + 1e-9, &tol));

// Exact match
assert!(approximately_equal(1.0, 1.0, &tol));

§Zero Tolerance (Exact Comparison)

use num_valid::scalars::{AbsoluteTolerance, approximately_equal};

let exact_tol = AbsoluteTolerance::<f64>::zero();

// Only exact matches pass
assert!(approximately_equal(1.0, 1.0, &exact_tol));
assert!(!approximately_equal(1.0, 1.0 + 1e-15, &exact_tol));

§Negative Values

use num_valid::scalars::{AbsoluteTolerance, approximately_equal};
use try_create::TryNew;

let tol = AbsoluteTolerance::try_new(0.1_f64).unwrap();

// Works with negative values
assert!(approximately_equal(-5.0, -5.05, &tol));
assert!(!approximately_equal(-5.0, -5.2, &tol));

§When to Use

§See Also