approx_equal(x, y [, tol [, rel]]) => True|False Return True if numbers x and y are approximately equal, to within some margin of error, otherwise return False. Numbers which compare equal will also compare approximately equal. x is approximately equal to y if the difference betwee
(x, y, tol=1e-12, rel=1e-7)
| 86 | |
| 87 | |
| 88 | def approx_equal(x, y, tol=1e-12, rel=1e-7): |
| 89 | """approx_equal(x, y [, tol [, rel]]) => True|False |
| 90 | |
| 91 | Return True if numbers x and y are approximately equal, to within some |
| 92 | margin of error, otherwise return False. Numbers which compare equal |
| 93 | will also compare approximately equal. |
| 94 | |
| 95 | x is approximately equal to y if the difference between them is less than |
| 96 | an absolute error tol or a relative error rel, whichever is bigger. |
| 97 | |
| 98 | If given, both tol and rel must be finite, non-negative numbers. If not |
| 99 | given, default values are tol=1e-12 and rel=1e-7. |
| 100 | |
| 101 | >>> approx_equal(1.2589, 1.2587, tol=0.0003, rel=0) |
| 102 | True |
| 103 | >>> approx_equal(1.2589, 1.2587, tol=0.0001, rel=0) |
| 104 | False |
| 105 | |
| 106 | Absolute error is defined as abs(x-y); if that is less than or equal to |
| 107 | tol, x and y are considered approximately equal. |
| 108 | |
| 109 | Relative error is defined as abs((x-y)/x) or abs((x-y)/y), whichever is |
| 110 | smaller, provided x or y are not zero. If that figure is less than or |
| 111 | equal to rel, x and y are considered approximately equal. |
| 112 | |
| 113 | Complex numbers are not directly supported. If you wish to compare to |
| 114 | complex numbers, extract their real and imaginary parts and compare them |
| 115 | individually. |
| 116 | |
| 117 | NANs always compare unequal, even with themselves. Infinities compare |
| 118 | approximately equal if they have the same sign (both positive or both |
| 119 | negative). Infinities with different signs compare unequal; so do |
| 120 | comparisons of infinities with finite numbers. |
| 121 | """ |
| 122 | if tol < 0 or rel < 0: |
| 123 | raise ValueError('error tolerances must be non-negative') |
| 124 | # NANs are never equal to anything, approximately or otherwise. |
| 125 | if math.isnan(x) or math.isnan(y): |
| 126 | return False |
| 127 | # Numbers which compare equal also compare approximately equal. |
| 128 | if x == y: |
| 129 | # This includes the case of two infinities with the same sign. |
| 130 | return True |
| 131 | if math.isinf(x) or math.isinf(y): |
| 132 | # This includes the case of two infinities of opposite sign, or |
| 133 | # one infinity and one finite number. |
| 134 | return False |
| 135 | # Two finite numbers. |
| 136 | actual_error = abs(x - y) |
| 137 | allowed_error = max(tol, rel*max(abs(x), abs(y))) |
| 138 | return actual_error <= allowed_error |
| 139 | |
| 140 | |
| 141 | # This class exists only as somewhere to stick a docstring containing |
no test coverage detected
searching dependent graphs…