Fail if the two floating-point numbers are not almost equal. Determine whether floating-point values a and b are equal to within a (small) rounding error. The default values for rel_err and abs_err are chosen to be suitable for platforms where a float is represented
(self, a, b, rel_err = 2e-15, abs_err = 5e-323,
msg=None)
| 67 | self.test_values.close() |
| 68 | |
| 69 | def rAssertAlmostEqual(self, a, b, rel_err = 2e-15, abs_err = 5e-323, |
| 70 | msg=None): |
| 71 | """Fail if the two floating-point numbers are not almost equal. |
| 72 | |
| 73 | Determine whether floating-point values a and b are equal to within |
| 74 | a (small) rounding error. The default values for rel_err and |
| 75 | abs_err are chosen to be suitable for platforms where a float is |
| 76 | represented by an IEEE 754 double. They allow an error of between |
| 77 | 9 and 19 ulps. |
| 78 | """ |
| 79 | |
| 80 | # special values testing |
| 81 | if math.isnan(a): |
| 82 | if math.isnan(b): |
| 83 | return |
| 84 | self.fail(msg or '{!r} should be nan'.format(b)) |
| 85 | |
| 86 | if math.isinf(a): |
| 87 | if a == b: |
| 88 | return |
| 89 | self.fail(msg or 'finite result where infinity expected: ' |
| 90 | 'expected {!r}, got {!r}'.format(a, b)) |
| 91 | |
| 92 | # if both a and b are zero, check whether they have the same sign |
| 93 | # (in theory there are examples where it would be legitimate for a |
| 94 | # and b to have opposite signs; in practice these hardly ever |
| 95 | # occur). |
| 96 | if not a and not b: |
| 97 | if math.copysign(1., a) != math.copysign(1., b): |
| 98 | self.fail(msg or 'zero has wrong sign: expected {!r}, ' |
| 99 | 'got {!r}'.format(a, b)) |
| 100 | |
| 101 | # if a-b overflows, or b is infinite, return False. Again, in |
| 102 | # theory there are examples where a is within a few ulps of the |
| 103 | # max representable float, and then b could legitimately be |
| 104 | # infinite. In practice these examples are rare. |
| 105 | try: |
| 106 | absolute_error = abs(b-a) |
| 107 | except OverflowError: |
| 108 | pass |
| 109 | else: |
| 110 | # test passes if either the absolute error or the relative |
| 111 | # error is sufficiently small. The defaults amount to an |
| 112 | # error of between 9 ulps and 19 ulps on an IEEE-754 compliant |
| 113 | # machine. |
| 114 | if absolute_error <= max(abs_err, rel_err * abs(a)): |
| 115 | return |
| 116 | self.fail(msg or |
| 117 | '{!r} and {!r} are not sufficiently close'.format(a, b)) |
| 118 | |
| 119 | def test_constants(self): |
| 120 | e_expected = 2.71828182845904523536 |
no test coverage detected