diff options
author | Damien George <damien@micropython.org> | 2025-05-20 10:34:56 +1000 |
---|---|---|
committer | Damien George <damien@micropython.org> | 2025-05-22 17:19:03 +1000 |
commit | 49f81d5046aaeb31f90626426363ae2518dbd810 (patch) | |
tree | 637024c0ef53f88f8744d8377ad7a405a7acf311 /tests/float/math_constants.py | |
parent | dc1af386a81f0238d809b2443714dc8feba5f174 (diff) |
tests/float/math_constants.py: Test actual e and pi constant values.
The existing test for `math.e` and `math.pi` constants can fail on certain
targets if the functions `math.exp()` and/or `math.cos()` are not accurate
enough (eg out by an LSB of float precision). For example this test
currently fails on PYBD_SF6 which uses double precision floats (and that's
due to the `lib/libm_dbl/exp.c` implementation not being exact).
This commit changes this constant test so that it tests the actual constant
value, not the evaluation of `exp()` and `cos()` functions.
Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'tests/float/math_constants.py')
-rw-r--r-- | tests/float/math_constants.py | 27 |
1 files changed, 23 insertions, 4 deletions
diff --git a/tests/float/math_constants.py b/tests/float/math_constants.py index 2e4c32105..21d822a01 100644 --- a/tests/float/math_constants.py +++ b/tests/float/math_constants.py @@ -1,11 +1,30 @@ # Tests various constants of the math module. + +import sys + try: - import math - from math import exp, cos + from array import array + from math import e, pi except ImportError: print("SKIP") raise SystemExit -print(math.e == exp(1.0)) +# Hexadecimal representations of e and pi constants. +e_truth_single = 0x402DF854 +pi_truth_single = 0x40490FDB +e_truth_double = 0x4005BF0A8B145769 +pi_truth_double = 0x400921FB54442D18 + +# Detect the floating-point precision of the system, to determine the exact values of +# the constants (parsing the float from a decimal string can lead to inaccuracies). +if float("1e300") == float("inf"): + # Single precision floats. + e_truth = array("f", e_truth_single.to_bytes(4, sys.byteorder))[0] + pi_truth = array("f", pi_truth_single.to_bytes(4, sys.byteorder))[0] +else: + # Double precision floats. + e_truth = array("d", e_truth_double.to_bytes(8, sys.byteorder))[0] + pi_truth = array("d", pi_truth_double.to_bytes(8, sys.byteorder))[0] -print(cos(math.pi)) +print("e:", e == e_truth or (e, e_truth, e - e_truth)) +print("pi:", pi == pi_truth or (pi, pi_truth, pi - pi_truth)) |