VTK  9.0.1
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 
39 template <class A>
40 bool FuzzyCompare(A a, A b)
41 {
42  return fabs(a - b) < std::numeric_limits<A>::epsilon();
43 }
44 
48 template <class A>
49 bool FuzzyCompare(A a, A b, A epsilon)
50 {
51  return fabs(a - b) < epsilon;
52 }
53 
57 template <class A>
58 A SafeDivision(A a, A b)
59 {
60  // Avoid overflow
61  if ((b < static_cast<A>(1)) && (a > b * std::numeric_limits<A>::max()))
62  {
64  }
65 
66  // Avoid underflow
67  if ((a == static_cast<A>(0)) ||
68  ((b > static_cast<A>(1)) && (a < b * std::numeric_limits<A>::min())))
69  {
70  return static_cast<A>(0);
71  }
72 
73  // safe to do the division
74  return (a / b);
75 }
76 
78 
82 template <class A>
83 bool NearlyEqual(A a, A b, A tol = std::numeric_limits<A>::epsilon())
84 {
85  A absdiff = fabs(a - b);
86  A d1 = vtkMathUtilities::SafeDivision<A>(absdiff, fabs(a));
87  A d2 = vtkMathUtilities::SafeDivision<A>(absdiff, fabs(b));
89 
90  if ((d1 <= tol) || (d2 <= tol))
91  {
92  return true;
93  }
94  return false;
95 }
96 
97 } // End vtkMathUtilities namespace.
98 
99 #endif // vtkMathUtilities_h
100 // 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...
bool FuzzyCompare(A a, A b)
Perform a fuzzy compare of floats/doubles.
A SafeDivision(A a, A b)
Performs safe division that catches overflow and underflow.
#define max(a, b)