ITK  4.9.0
Insight Segmentation and Registration Toolkit
itkMath.h
Go to the documentation of this file.
1 /*=========================================================================
2  *
3  * Copyright Insight Software Consortium
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0.txt
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  *=========================================================================*/
18 /*=========================================================================
19  *
20  * Portions of this file are subject to the VTK Toolkit Version 3 copyright.
21  *
22  * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
23  *
24  * For complete copyright, license and disclaimer of warranty information
25  * please refer to the NOTICE file at the top of the ITK source tree.
26  *
27  *=========================================================================*/
28 #ifndef itkMath_h
29 #define itkMath_h
30 
31 #include "itkIntTypes.h"
32 #include "itkMathDetail.h"
33 #include "itkConceptChecking.h"
34 #include "itkNumericTraits.h"
35 
36 namespace itk
37 {
38 namespace Math
39 {
40 // These constants originate from VXL's vnl_math.h. They have been
41 // moved here to improve visibility, and to ensure that the constants
42 // are available during compile time ( as opposed to static const
43 // member vaiables ).
44 
45 
47 static const double e = 2.7182818284590452354;
49 static const double log2e = 1.4426950408889634074;
51 static const double log10e = 0.43429448190325182765;
53 static const double ln2 = 0.69314718055994530942;
55 static const double ln10 = 2.30258509299404568402;
57 static const double pi = 3.14159265358979323846;
59 static const double pi_over_2 = 1.57079632679489661923;
61 static const double pi_over_4 = 0.78539816339744830962;
63 static const double one_over_pi = 0.31830988618379067154;
65 static const double two_over_pi = 0.63661977236758134308;
67 static const double two_over_sqrtpi = 1.12837916709551257390;
69 static const double one_over_sqrt2pi = 0.39894228040143267794;
71 static const double sqrt2 = 1.41421356237309504880;
73 static const double sqrt1_2 = 0.70710678118654752440;
74 
78 #define itkTemplateFloatingToIntegerMacro(name) \
79  template< typename TReturn, typename TInput > \
80  inline TReturn name(TInput x) \
81  { \
82  \
83  if ( sizeof( TReturn ) <= 4 ) \
84  { \
85  return static_cast< TReturn >( Detail::name##_32(x) ); \
86  } \
87  else if ( sizeof( TReturn ) <= 8 ) \
88  { \
89  return static_cast< TReturn >( Detail::name##_64(x) ); \
90  } \
91  else \
92  { \
93  return static_cast< TReturn >( Detail::name##_base< TReturn, TInput >(x) ); \
94  } \
95  }
96 
97 
118 
142 
150 template< typename TReturn, typename TInput >
151 inline TReturn Round(TInput x) { return RoundHalfIntegerUp< TReturn, TInput >(x); }
152 
166 
178 
179 #undef itkTemplateFloatingToIntegerMacro
180 
181 template< typename TReturn, typename TInput >
182 inline TReturn CastWithRangeCheck(TInput x)
183 {
184 #ifdef ITK_USE_CONCEPT_CHECKING
185  itkConceptMacro( OnlyDefinedForIntegerTypes1, ( itk::Concept::IsInteger< TReturn > ) );
186  itkConceptMacro( OnlyDefinedForIntegerTypes2, ( itk::Concept::IsInteger< TInput > ) );
187 #endif // ITK_USE_CONCEPT_CHECKING
188 
189  TReturn ret = static_cast< TReturn >( x );
190  if ( sizeof( TReturn ) > sizeof( TInput )
192  {
193  // if the output type is bigger and we are not converting a signed
194  // integer to an unsigned integer then we have no problems
195  return ret;
196  }
197  else if ( sizeof( TReturn ) >= sizeof( TInput ) )
198  {
200  {
201  itk::RangeError _e(__FILE__, __LINE__);
202  throw _e;
203  }
204  }
205  else if ( static_cast< TInput >( ret ) != x
207  {
208  itk::RangeError _e(__FILE__, __LINE__);
209  throw _e;
210  }
211  return ret;
212 }
213 
220 template <typename T>
221 inline typename Detail::FloatIEEE<T>::IntType
222 FloatDifferenceULP( T x1, T x2 )
223 {
224  Detail::FloatIEEE<T> x1f(x1);
225  Detail::FloatIEEE<T> x2f(x2);
226  return x1f.AsULP() - x2f.AsULP();
227 }
228 
259 template <typename T>
260 inline bool
261 FloatAlmostEqual( T x1, T x2,
262  typename Detail::FloatIEEE<T>::IntType maxUlps = 4,
263  typename Detail::FloatIEEE<T>::FloatType maxAbsoluteDifference = 0.1*itk::NumericTraits<T>::epsilon() )
264 {
265  // Check if the numbers are really close -- needed
266  // when comparing numbers near zero.
267  const T absDifference = std::abs(x1 - x2);
268  if ( absDifference <= maxAbsoluteDifference )
269  {
270  return true;
271  }
272 
273 #if defined(__APPLE__) && (__clang_major__ == 3) && (__clang_minor__ == 0) && defined(NDEBUG) && defined(__x86_64__)
274  Detail::FloatIEEE<T> x1f(x1);
275  Detail::FloatIEEE<T> x2f(x2);
276  double x1fAsULP = static_cast<double>(x1f.AsULP());
277  double x2fAsULP = static_cast<double>(x2f.AsULP());
278  double ulps = x1fAsULP - x2fAsULP;
279  if(ulps < 0)
280  {
281  ulps = -ulps;
282  }
283  return ulps <= static_cast<double>(maxUlps);
284 #else
286  ulps = FloatDifferenceULP(x1, x2);
287  if(ulps < 0)
288  {
289  ulps = -ulps;
290  }
291  return ulps <= maxUlps;
292 #endif
293 }
294 
295 // The following code cannot be moved to the itkMathDetail.h file without introducing circular dependencies
296 namespace Detail // The Detail namespace holds the templates used by AlmostEquals
297 {
298 // The following structs and templates are used to choose
299 // which version of the AlmostEquals function
300 // should be implemented base on input parameter types
301 
302 // Structs for choosing AlmostEquals function
303 
305 {
306  template <typename TFloatType1, typename TFloatType2>
307  static bool AlmostEqualsFunction(TFloatType1 x1, TFloatType2 x2)
308  {
309  return FloatAlmostEqual<double>(x1, x2);
310  }
311 
312  template <typename TFloatType1, typename TFloatType2>
313  static bool
314  AlmostEqualsFunction(double x1, double x2)
315  {
316  return FloatAlmostEqual<double>(x1, x2);
317  }
318 
319  template <typename TFloatType1, typename TFloatType2>
320  static bool
321  AlmostEqualsFunction(double x1, float x2)
322  {
323  return FloatAlmostEqual<float>(x1, x2);
324  }
325 
326  template <typename TFloatType1, typename TFloatType2>
327  static bool
328  AlmostEqualsFunction(float x1, double x2)
329  {
330  return FloatAlmostEqual<float>(x1, x2);
331  }
332 
333  template <typename TFloatType1, typename TFloatType2>
334  static bool
335  AlmostEqualsFunction(float x1, float x2)
336  {
337  return FloatAlmostEqual<float>(x1, x2);
338  }
339 };
340 
342 {
343  template <typename TFloatType, typename TIntType>
344  static bool AlmostEqualsFunction(TFloatType floatingVariable, TIntType integerVariable)
345  {
346  return FloatAlmostEqual<TFloatType> (floatingVariable, integerVariable);
347  }
348 };
349 
351 {
352  template <typename TIntType, typename TFloatType>
353  static bool AlmostEqualsFunction(TIntType integerVariable, TFloatType floatingVariable)
354  {
355  return AlmostEqualsFloatVsInteger::AlmostEqualsFunction(floatingVariable, integerVariable);
356  }
357 };
358 
360 {
361  template <typename TSignedInt, typename TUnsignedInt>
362  static bool AlmostEqualsFunction(TSignedInt signedVariable, TUnsignedInt unsignedVariable)
363  {
364  if(signedVariable < 0) return false;
365  if( unsignedVariable > static_cast< size_t >(itk::NumericTraits<TSignedInt>::max()) ) return false;
366  return signedVariable == static_cast< TSignedInt >(unsignedVariable);
367  }
368 };
369 
371 {
372  template <typename TUnsignedInt, typename TSignedInt>
373  static bool AlmostEqualsFunction(TUnsignedInt unsignedVariable, TSignedInt signedVariable)
374  {
375  return AlmostEqualsSignedVsUnsigned::AlmostEqualsFunction(signedVariable, unsignedVariable);
376  }
377 };
378 
380 {
381  template <typename TIntegerType1, typename TIntegerType2>
382  static bool AlmostEqualsFunction(TIntegerType1 x1, TIntegerType2 x2)
383  {
384  return x1 == x2;
385  }
386 };
387 // end of structs that choose the specific AlmostEquals function
388 
389 // Selector structs, these select the correct case based on its types
390 // input1 is int? input 1 is signed? input2 is int? input 2 is signed?
391 template<bool TInput1IsIntger, bool TInput1IsSigned, bool TInput2IsInteger, bool TInput2IsSigned>
393 { // default case
395 };
396 
398 template<>
399 struct AlmostEqualsFunctionSelector < false, true, false, true>
400 // floating type v floating type
401 {
403 };
404 
405 template<>
406 struct AlmostEqualsFunctionSelector <false, true, true, true>
407 // float vs signed int
408 {
409  typedef AlmostEqualsFloatVsInteger SelectedVersion;
410 };
411 
412 template<>
413 struct AlmostEqualsFunctionSelector <false, true, true,false>
414 // float vs unsigned int
415 {
416  typedef AlmostEqualsFloatVsInteger SelectedVersion;
417 };
418 
419 template<>
420 struct AlmostEqualsFunctionSelector <true, false, false, true>
421 // unsigned int vs float
422 {
423  typedef AlmostEqualsIntegerVsFloat SelectedVersion;
424 };
425 
426 template<>
427 struct AlmostEqualsFunctionSelector <true, true, false, true>
428 // signed int vs float
429 {
430  typedef AlmostEqualsIntegerVsFloat SelectedVersion;
431 };
432 
433 template<>
434 struct AlmostEqualsFunctionSelector<true, true, true, false>
435 // signed vs unsigned
436 {
437  typedef AlmostEqualsSignedVsUnsigned SelectedVersion;
438 };
439 
440 template<>
441 struct AlmostEqualsFunctionSelector<true, false, true, true>
442 // unsigned vs signed
443 {
444  typedef AlmostEqualsUnsignedVsSigned SelectedVersion;
445 };
446 
447 template<>
448 struct AlmostEqualsFunctionSelector<true, true, true, true>
449 // signed vs signed
450 {
451  typedef AlmostEqualsPlainOldEquals SelectedVersion;
452 };
453 
454 template<>
455 struct AlmostEqualsFunctionSelector<true, false, true, false>
456 // unsigned vs unsigned
457 {
458  typedef AlmostEqualsPlainOldEquals SelectedVersion;
459 };
460 // end of AlmostEqualsFunctionSelector structs
461 
462  // The implementor tells the selector what to do
463 template<typename TInputType1, typename TInputType2>
464 struct AlmostEqualsScalarImplementer
465 {
466  static const bool TInputType1IsInteger = itk::NumericTraits<TInputType1>::IsInteger;
467  static const bool TInputType1IsSigned = itk::NumericTraits<TInputType1>::IsSigned;
468  static const bool TInputType2IsInteger = itk::NumericTraits<TInputType2>::IsInteger;
469  static const bool TInputType2IsSigned = itk::NumericTraits<TInputType2>::IsSigned;
470 
471  typedef typename AlmostEqualsFunctionSelector< TInputType1IsInteger, TInputType1IsSigned,
472  TInputType2IsInteger, TInputType2IsSigned >::SelectedVersion SelectedVersion;
473 };
474 
475 // The AlmostEqualsScalarComparer returns the result of an
476 // approximate comparison between two scalar values of
477 // potentially different data types.
478 template <typename TScalarType1, typename TScalarType2>
479 static bool
480 AlmostEqualsScalarComparer( TScalarType1 x1, TScalarType2 x2 )
481 {
482  return AlmostEqualsScalarImplementer<TScalarType1, TScalarType2>::SelectedVersion:: template AlmostEqualsFunction<TScalarType1, TScalarType2>(x1, x2);
483 }
484 
485 // The following structs are used to evaluate approximate comparisons between
486 // complex and scalar values of potentially different types.
487 
488 // Comparisons between scalar types use the AlmostEqualsScalarComparer function.
489 struct AlmostEqualsScalarVsScalar
490 {
491  template <typename TScalarType1, typename TScalarType2>
492  static bool
493  AlmostEqualsFunction(TScalarType1 x1, TScalarType2 x2)
494  {
495  return AlmostEqualsScalarComparer(x1, x2);
496  }
497 };
498 
499 // Comparisons between two complex values compare the real and imaginary components
500 // separately with the AlmostEqualsScalarComparer function.
501 struct AlmostEqualsComplexVsComplex
502 {
503  template <typename TComplexType1, typename TComplexType2>
504  static bool
505  AlmostEqualsFunction(TComplexType1 x1, TComplexType2 x2)
506  {
507  return AlmostEqualsScalarComparer(x1.real(), x2.real()) && AlmostEqualsScalarComparer( x1.imag(), x2.imag() );
508  }
509 };
510 
511 // Comparisons between complex and scalar values first check to see if the imaginary component
512 // of the complex value is approximately 0. Then a ScalarComparison is done between the real
513 // part of the complex number and the scalar value.
514 struct AlmostEqualsScalarVsComplex
515 {
516  template <typename TScalarType, typename TComplexType>
517  static bool
518  AlmostEqualsFunction(TScalarType scalarVariable, TComplexType complexVariable)
519  {
520  if( !AlmostEqualsScalarComparer( complexVariable.imag(), itk::NumericTraits< typename itk::NumericTraits< TComplexType >::ValueType >::ZeroValue() ) )
521  {
522  return false;
523  }
524  return AlmostEqualsScalarComparer(scalarVariable, complexVariable.real());
525  }
526 };
527 
528 struct AlmostEqualsComplexVsScalar
529 {
530  template <typename TComplexType, typename TScalarType>
531  static bool
532  AlmostEqualsFunction(TComplexType complexVariable, TScalarType scalarVariable)
533  {
534  return AlmostEqualsScalarVsComplex::AlmostEqualsFunction(scalarVariable, complexVariable);
535  }
536 };
537 
538 // The AlmostEqualsComplexChooser structs choose the correct case
539 // from the input parameter types' IsComplex property
540 // The default case is scalar vs scalar
541 template < bool T1IsComplex, bool T2IsComplex > //Default is false, false
542 struct AlmostEqualsComplexChooser
543 {
544  typedef AlmostEqualsScalarVsScalar ChosenVersion;
545 };
546 
547 template <>
548 struct AlmostEqualsComplexChooser< true, true >
549 {
550  typedef AlmostEqualsComplexVsComplex ChosenVersion;
551 };
552 
553 template <>
554 struct AlmostEqualsComplexChooser< false, true >
555 {
556  typedef AlmostEqualsScalarVsComplex ChosenVersion;
557 };
558 
559 template <>
560 struct AlmostEqualsComplexChooser< true, false>
561 {
562  typedef AlmostEqualsComplexVsScalar ChosenVersion;
563 };
564 // End of AlmostEqualsComplexChooser structs.
565 
566 // The AlmostEqualsComplexImplementer determines which of the input
567 // parameters are complex and which are real, and sends that information
568 // to the AlmostEqualsComplexChooser structs to determine the proper
569 // type of evaluation.
570 template <typename T1, typename T2>
571 struct AlmostEqualsComplexImplementer
572 {
573  static const bool T1IsComplex = NumericTraits< T1 >::IsComplex;
574  static const bool T2IsComplex = NumericTraits< T2 >::IsComplex;
575 
576  typedef typename AlmostEqualsComplexChooser< T1IsComplex, T2IsComplex >::ChosenVersion ChosenVersion;
577 };
579 
580 } // end namespace Detail
581 
624 // The AlmostEquals function
625 template <typename T1, typename T2>
626 inline bool
627 AlmostEquals( T1 x1, T2 x2 )
628 {
629  return Detail::AlmostEqualsComplexImplementer<T1,T2>::ChosenVersion::AlmostEqualsFunction(x1, x2);
630 }
631 
632 // The NotAlmostEquals function
633 template <typename T1, typename T2>
634 inline bool
635 NotAlmostEquals( T1 x1, T2 x2 )
636 {
637  return ! AlmostEquals( x1, x2 );
638 }
639 
640 
662 // The ExactlyEquals function
663 template <typename TInput1, typename TInput2>
664 inline bool
665 ExactlyEquals( const TInput1 & x1, const TInput2 & x2 )
666 {
667 CLANG_PRAGMA_PUSH
668 CLANG_SUPPRESS_Wfloat_equal
669  return x1 == x2;
670 CLANG_PRAGMA_POP
671 }
672 
673 //The NotExactlyEquals function
674 template <typename TInput1, typename TInput2>
675 inline bool
676 NotExactlyEquals( const TInput1 & x1, const TInput2 & x2 )
677 {
678  return !ExactlyEquals(x1, x2);
679 }
680 
681 
686 ITKCommon_EXPORT bool IsPrime( unsigned short n );
687 ITKCommon_EXPORT bool IsPrime( unsigned int n );
688 ITKCommon_EXPORT bool IsPrime( unsigned long n );
689 ITKCommon_EXPORT bool IsPrime( unsigned long long n );
691 
692 
694 ITKCommon_EXPORT unsigned short GreatestPrimeFactor( unsigned short n );
695 ITKCommon_EXPORT unsigned int GreatestPrimeFactor( unsigned int n );
696 ITKCommon_EXPORT unsigned long GreatestPrimeFactor( unsigned long n );
697 ITKCommon_EXPORT unsigned long long GreatestPrimeFactor( unsigned long long n );
699 
700 } // end namespace Math
701 } // end namespace itk
702 #endif // end of itkMath.h
static bool AlmostEqualsFunction(double x1, float x2)
Definition: itkMath.h:321
static bool AlmostEqualsFunction(TSignedInt signedVariable, TUnsignedInt unsignedVariable)
Definition: itkMath.h:362
static bool AlmostEqualsFunction(float x1, double x2)
Definition: itkMath.h:328
static const double two_over_pi
Definition: itkMath.h:65
TReturn Round(TInput x)
Round towards nearest integer (This is a synonym for RoundHalfIntegerUp)
Definition: itkMath.h:151
RoundHalfIntegerUp(TInput x)
Round towards nearest integer.
static const double ln2
Definition: itkMath.h:53
static bool AlmostEqualsFunction(TIntType integerVariable, TFloatType floatingVariable)
Definition: itkMath.h:353
static const double pi
Definition: itkMath.h:57
static const double two_over_sqrtpi
Definition: itkMath.h:67
static const double one_over_sqrt2pi
Definition: itkMath.h:69
Floor(TInput x)
Round towards minus infinity.
bool ExactlyEquals(const TInput1 &x1, const TInput2 &x2)
Return the result of an exact comparison between two scalar values of potetially different types...
Definition: itkMath.h:665
TReturn CastWithRangeCheck(TInput x)
Definition: itkMath.h:182
ITKCommon_EXPORT unsigned short GreatestPrimeFactor(unsigned short n)
static const double e
The base of the natural logarithm or Euler&#39;s number
Definition: itkMath.h:47
static bool IsPositive(T val)
static bool AlmostEqualsFunction(TUnsignedInt unsignedVariable, TSignedInt signedVariable)
Definition: itkMath.h:373
static bool AlmostEqualsFunction(TFloatType floatingVariable, TIntType integerVariable)
Definition: itkMath.h:344
static const double pi_over_2
Definition: itkMath.h:59
Detail::FloatIEEE< T >::IntType FloatDifferenceULP(T x1, T x2)
Return the signed distance in ULPs (units in the last place) between two floats.
Definition: itkMath.h:222
static const double ln10
Definition: itkMath.h:55
#define itkTemplateFloatingToIntegerMacro(name)
Definition: itkMath.h:78
static const double sqrt2
Definition: itkMath.h:71
static const double log10e
Definition: itkMath.h:51
FloatIEEETraits< T >::IntType IntType
static bool AlmostEqualsFunction(TIntegerType1 x1, TIntegerType2 x2)
Definition: itkMath.h:382
bool NotExactlyEquals(const TInput1 &x1, const TInput2 &x2)
Definition: itkMath.h:676
static const double log2e
Definition: itkMath.h:49
Ceil(TInput x)
Round towards plus infinity.
static const double one_over_pi
Definition: itkMath.h:63
static bool AlmostEqualsFunction(float x1, float x2)
Definition: itkMath.h:335
bool AlmostEquals(T1 x1, T2 x2)
Provide consistent equality checks between values of potentially different scalar or complex types...
Definition: itkMath.h:627
bool FloatAlmostEqual(T x1, T x2, typename Detail::FloatIEEE< T >::IntType maxUlps=4, typename Detail::FloatIEEE< T >::FloatType maxAbsoluteDifference=0.1 *itk::NumericTraits< T >::epsilon())
Compare two floats and return if they are effectively equal.
Definition: itkMath.h:261
static const double pi_over_4
Definition: itkMath.h:61
AlmostEqualsPlainOldEquals SelectedVersion
Definition: itkMath.h:394
static bool AlmostEqualsFunction(TFloatType1 x1, TFloatType2 x2)
Definition: itkMath.h:307
Define additional traits for native types such as int or float.
bool NotAlmostEquals(T1 x1, T2 x2)
Definition: itkMath.h:635
static const double sqrt1_2
Definition: itkMath.h:73
static bool AlmostEqualsFunction(double x1, double x2)
Definition: itkMath.h:314
RoundHalfIntegerToEven(TInput x)
Round towards nearest integer.
#define itkConceptMacro(name, concept)
ITKCommon_EXPORT bool IsPrime(unsigned short n)