VTK
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 
30 #ifndef vtkMathUtilities_h
31 #define vtkMathUtilities_h
32 
33 #include <cmath>
34 #include <limits>
35 
37 {
38 
42 template<class A>
43 bool FuzzyCompare(A a, A b)
44 {
45  return fabs(a - b) < std::numeric_limits<A>::epsilon();
46 }
47 
51 template<class A>
52 bool FuzzyCompare(A a, A b, A epsilon)
53 {
54  return fabs(a - b) < epsilon;
55 }
56 
60 template<class A>
61 A SafeDivision(A a, A b)
62 {
63  // Avoid overflow
64  if( (b < static_cast<A>(1)) && (a > b*std::numeric_limits<A>::max()) )
65  {
67  }
68 
69  // Avoid underflow
70  if( (a == static_cast<A>(0)) ||
71  ((b > static_cast<A>(1)) && (a < b*std::numeric_limits<A>::min())) )
72  {
73  return static_cast<A>(0);
74  }
75 
76  // safe to do the division
77  return( a/b );
78 }
79 
81 
85 template<class A>
86 bool NearlyEqual(A a, A b, A tol=std::numeric_limits<A>::epsilon())
87 {
88  A absdiff = fabs(a-b);
89  A d1 = vtkMathUtilities::SafeDivision<A>(absdiff,fabs(a));
90  A d2 = vtkMathUtilities::SafeDivision<A>(absdiff,fabs(b));
92 
93  if( (d1 <= tol) || (d2 <= tol) )
94  {
95  return true;
96  }
97  return false;
98 }
99 
100 } // End vtkMathUtilities namespace.
101 
102 #endif // vtkMathUtilities_h
103 // 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)