VTK  9.1.0
vtkMathUtilities.h
Go to the documentation of this file.
1/*=========================================================================
2
3 Program: Visualization Toolkit
4 Module: vtkMathUtilities.h
5
6 Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
7 All rights reserved.
8 See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
9
10 This software is distributed WITHOUT ANY WARRANTY; without even
11 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
12 PURPOSE. See the above copyright notice for more information.
13
14=========================================================================*/
15
27#ifndef vtkMathUtilities_h
28#define vtkMathUtilities_h
29
30#include <cmath>
31#include <limits>
32
34{
35
39template <class A>
40bool FuzzyCompare(A a, A b, A epsilon = std::numeric_limits<A>::epsilon())
41{
42 return fabs(a - b) < epsilon;
43}
44
48template <class A>
49A SafeDivision(A a, A b)
50{
51 // Avoid overflow
52 if ((b < static_cast<A>(1)) && (a > b * std::numeric_limits<A>::max()))
53 {
55 }
56
57 // Avoid underflow
58 if ((a == static_cast<A>(0)) ||
59 ((b > static_cast<A>(1)) && (a < b * std::numeric_limits<A>::min())))
60 {
61 return static_cast<A>(0);
62 }
63
64 // safe to do the division
65 return (a / b);
66}
67
72template <class A>
73bool NearlyEqual(A a, A b, A tol = std::numeric_limits<A>::epsilon())
74{
75 A absdiff = fabs(a - b);
76 A d1 = vtkMathUtilities::SafeDivision<A>(absdiff, fabs(a));
77 A d2 = vtkMathUtilities::SafeDivision<A>(absdiff, fabs(b));
78
79 return ((d1 <= tol) || (d2 <= tol));
80}
81
82} // End vtkMathUtilities namespace.
83
84#endif // vtkMathUtilities_h
85// VTK-HeaderTest-Exclude: vtkMathUtilities.h
bool NearlyEqual(A a, A b, A tol=std::numeric_limits< A >::epsilon())
A slightly different fuzzy comparator that checks if two values are "nearly" equal based on Knuth,...
A SafeDivision(A a, A b)
Performs safe division that catches overflow and underflow.
bool FuzzyCompare(A a, A b, A epsilon=std::numeric_limits< A >::epsilon())
Perform a fuzzy compare of floats/doubles, specify the allowed tolerance.
#define max(a, b)