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 
29 #ifndef vtkMathUtilities_h
30 #define vtkMathUtilities_h
31 
32 #include <cmath>
33 #include <limits>
34 
36 {
37 
39 
40 template<class A>
41 bool FuzzyCompare(A a, A b)
42 {
43  return fabs(a - b) < std::numeric_limits<A>::epsilon();
44 }
46 
48 
50 template<class A>
51 bool FuzzyCompare(A a, A b, A epsilon)
52 {
53  return fabs(a - b) < epsilon;
54 }
56 
58 
59 template<class A>
60 A SafeDivision(A a, A b)
61 {
62  // Avoid overflow
63  if( (b < static_cast<A>(1)) && (a > b*std::numeric_limits<A>::max()) )
64  {
66  }
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 
84 template<class A>
85 bool NearlyEqual(A a, A b, A tol=std::numeric_limits<A>::epsilon())
86 {
87  A absdiff = fabs(a-b);
88  A d1 = vtkMathUtilities::SafeDivision<A>(absdiff,fabs(a));
89  A d2 = vtkMathUtilities::SafeDivision<A>(absdiff,fabs(b));
91 
92  if( (d1 <= tol) || (d2 <= tol) )
93  {
94  return true;
95  }
96  return false;
97 }
98 
99 } // End vtkMathUtilities namespace.
100 
101 #endif // vtkMathUtilities_h
102 // VTK-HeaderTest-Exclude: vtkMathUtilities.h
bool NearlyEqual(A a, A b, A tol=std::numeric_limits< A >::epsilon())
bool FuzzyCompare(A a, A b)
A SafeDivision(A a, A b)
#define max(a, b)