VTK
|
00001 /*========================================================================= 00002 00003 Program: Visualization Toolkit 00004 Module: vtkMathUtilities.h 00005 00006 Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 00007 All rights reserved. 00008 See Copyright.txt or http://www.kitware.com/Copyright.htm for details. 00009 00010 This software is distributed WITHOUT ANY WARRANTY; without even 00011 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 00012 PURPOSE. See the above copyright notice for more information. 00013 00014 =========================================================================*/ 00015 00029 #ifndef __vtkMathUtilities_h 00030 #define __vtkMathUtilities_h 00031 00032 #include <cmath> 00033 #include <limits> 00034 00035 namespace vtkMathUtilities 00036 { 00037 00039 00040 template<class A> 00041 bool FuzzyCompare(A a, A b) 00042 { 00043 return fabs(a - b) < std::numeric_limits<A>::epsilon(); 00044 } 00046 00048 00050 template<class A> 00051 bool FuzzyCompare(A a, A b, A epsilon) 00052 { 00053 return fabs(a - b) < epsilon; 00054 } 00056 00058 00059 template<class A> 00060 A SafeDivision(A a, A b) 00061 { 00062 // Avoid overflow 00063 if( (b < static_cast<A>(1)) && (a > b*std::numeric_limits<A>::max()) ) 00064 { 00065 return std::numeric_limits<A>::max(); 00066 } 00068 00069 // Avoid underflow 00070 if( (a == static_cast<A>(0)) || 00071 ((b > static_cast<A>(1)) && (a < b*std::numeric_limits<A>::min())) ) 00072 { 00073 return static_cast<A>(0); 00074 } 00075 00076 // safe to do the division 00077 return( a/b ); 00078 } 00079 00081 00084 template<class A> 00085 bool NearlyEqual(A a, A b, A tol=std::numeric_limits<A>::epsilon()) 00086 { 00087 A absdiff = fabs(a-b); 00088 A d1 = vtkMathUtilities::SafeDivision<A>(absdiff,fabs(a)); 00089 A d2 = vtkMathUtilities::SafeDivision<A>(absdiff,fabs(b)); 00091 00092 if( (d1 <= tol) || (d2 <= tol) ) 00093 { 00094 return true; 00095 } 00096 return false; 00097 } 00098 00099 } // End vtkMathUtilities namespace. 00100 00101 #endif // __vtkMathUtilities_h 00102 // VTK-HeaderTest-Exclude: vtkMathUtilities.h