1b10005b4SLisandro Dalcin #include <petscsys.h> 2b10005b4SLisandro Dalcin 3b10005b4SLisandro Dalcin /*@C 4b10005b4SLisandro Dalcin PetscIsCloseAtTol - Returns whether the two floating point numbers 5b10005b4SLisandro Dalcin are close at given relative and absolute tolerances. 6b10005b4SLisandro Dalcin 7d8d19677SJose E. Roman Input Parameters: 8b10005b4SLisandro Dalcin + a - first floating point number 9b10005b4SLisandro Dalcin . b - second floating point number 10b10005b4SLisandro Dalcin . rtol - relative tolerance 11a2b725a8SWilliam Gropp - atol - absolute tolerances 12b10005b4SLisandro Dalcin 13a8d69d7bSBarry Smith Notes: https://www.python.org/dev/peps/pep-0485/ 14b10005b4SLisandro Dalcin 15b10005b4SLisandro Dalcin Level: beginner 16b10005b4SLisandro Dalcin @*/ 17*9371c9d4SSatish Balay PetscBool PetscIsCloseAtTol(PetscReal a, PetscReal b, PetscReal rtol, PetscReal atol) { 18b10005b4SLisandro Dalcin PetscReal diff; 19b10005b4SLisandro Dalcin /* NaN is not considered close to any other value, including NaN */ 20b10005b4SLisandro Dalcin if (PetscIsNanReal(a) || PetscIsNanReal(b)) return PETSC_FALSE; 21b10005b4SLisandro Dalcin /* Fast path for exact equality or two infinities of same sign */ 22b10005b4SLisandro Dalcin if (a == b) return PETSC_TRUE; 23b10005b4SLisandro Dalcin /* Handle two infinities of opposite sign */ 24b10005b4SLisandro Dalcin if (PetscIsInfReal(a) || PetscIsInfReal(b)) return PETSC_FALSE; 25b10005b4SLisandro Dalcin /* Cannot error if tolerances are negative */ 26*9371c9d4SSatish Balay rtol = PetscAbsReal(rtol); 27*9371c9d4SSatish Balay atol = PetscAbsReal(atol); 28b10005b4SLisandro Dalcin /* The regular check for difference within tolerances */ 29b10005b4SLisandro Dalcin diff = PetscAbsReal(b - a); 30b10005b4SLisandro Dalcin return ((diff <= PetscAbsReal(rtol * b)) || (diff <= PetscAbsReal(rtol * a)) || (diff <= atol)) ? PETSC_TRUE : PETSC_FALSE; 31b10005b4SLisandro Dalcin } 32