closeTo() is used to determine if the binary representation of two numbers are relatively close to each other. Numerical errors due to rounding errors build up over many operations, so it is almost impossible to get exact numbers and this is where closeTo() comes in. It shouldn't be used to determine if two numbers are mathematically close to each other. ref: http://www.cygnus-software.com/paper
| 106 | // ref: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm |
| 107 | // ref: http://www.gamedev.net/topic/653449-scriptmath-and-closeto/ |
| 108 | bool closeTo(float a, float b, float epsilon) |
| 109 | { |
| 110 | // Equal numbers and infinity will return immediately |
| 111 | if( a == b ) return true; |
| 112 | |
| 113 | // When very close to 0, we can use the absolute comparison |
| 114 | float diff = fabsf(a - b); |
| 115 | if( (a == 0 || b == 0) && (diff < epsilon) ) |
| 116 | return true; |
| 117 | |
| 118 | // Otherwise we need to use relative comparison to account for precision |
| 119 | return diff / (fabs(a) + fabs(b)) < epsilon; |
| 120 | } |
| 121 | |
| 122 | bool closeTo(double a, double b, double epsilon) |
| 123 | { |