summaryrefslogtreecommitdiff
path: root/tests/float
AgeCommit message (Collapse)Author
7 dayspy/parse: Add support for math module constants and float folding.Yoctopuce dev
Add a new MICROPY_COMP_CONST_FLOAT feature, enabled by in mpy-cross and when compiling with MICROPY_CONFIG_ROM_LEVEL_CORE_FEATURES. The new feature leverages the code of MICROPY_COMP_CONST_FOLDING to support folding of floating point constants. If MICROPY_COMP_MODULE_CONST is defined as well, math module constants are made available at compile time. For example: _DEG_TO_GRADIANT = const(math.pi / 180) _INVALID_VALUE = const(math.nan) A few corner cases had to be handled: - The float const folding code should not fold expressions resulting into complex results, as the mpy parser for complex immediates has limitations. - The constant generation code must distinguish between -0.0 and 0.0, which are different even if C consider them as ==. This change removes previous limitations on the use of `const()` expressions that would result in floating point number, so the test cases of micropython/const_error have to be updated. Additional test cases have been added to cover the new repr() code (from a previous commit). A few other simple test cases have been added to handle the use of floats in `const()` expressions, but the float folding code itself is also tested when running general float test cases, as float expressions often get resolved at compile-time (with this change). Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
8 dayspy/formatfloat: Improve accuracy of float formatting code.Yoctopuce dev
Following discussions in PR #16666, this commit updates the float formatting code to improve the `repr` reversibility, i.e. the percentage of valid floating point numbers that do parse back to the same number when formatted by `repr` (in CPython it's 100%). This new code offers a choice of 3 float conversion methods, depending on the desired tradeoff between code size and conversion precision: - BASIC method is the smallest code footprint - APPROX method uses an iterative method to approximate the exact representation, which is a bit slower but but does not have a big impact on code size. It provides `repr` reversibility on >99.8% of the cases in double precision, and on >98.5% in single precision (except with REPR_C, where reversibility is 100% as the last two bits are not taken into account). - EXACT method uses higher-precision floats during conversion, which provides perfect results but has a higher impact on code size. It is faster than APPROX method, and faster than the CPython equivalent implementation. It is however not available on all compilers when using FLOAT_IMPL_DOUBLE. Here is the table comparing the impact of the three conversion methods on code footprint on PYBV10 (using single-precision floats) and reversibility rate for both single-precision and double-precision floats. The table includes current situation as a baseline for the comparison: PYBV10 REPR_C FLOAT DOUBLE current = 364688 12.9% 27.6% 37.9% basic = 364812 85.6% 60.5% 85.7% approx = 365080 100.0% 98.5% 99.8% exact = 366408 100.0% 100.0% 100.0% Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
11 dayspy/objint_longlong: Fix longlong interoperability with floats.Yoctopuce dev
Current longlong implementation does not allow a float as RHS of mathematic operators, as it lacks the delegation code present in mpz. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-07-24all: Go back to using default ruff quote style.Damien George
Commit dc2fcfcc5511a371ff684f7d7772e7a7b479246d seems to have accidentally changed the ruff quote style to "preserve", instead of keeping it at the default which is "double". Put it back to the default and update relevant .py files with this rule. Signed-off-by: Damien George <damien@micropython.org>
2025-07-24py/obj: Fix REPR_C bias toward zero.Yoctopuce dev
Current implementation of REPR_C works by clearing the two lower bits of the mantissa to zero. As this happens after each floating point operation, this tends to bias floating point numbers towards zero, causing decimals like .9997 instead of rounded numbers. This is visible in test cases involving repeated computations, such as `tests/misc/rge_sm.py` for instance. The suggested fix fills in the missing bits by copying the previous two bits. Although this cannot recreate missing information, it fixes the bias by inserting plausible values for the lost bits, at a relatively low cost. Some float tests involving irrational numbers have to be softened in case of REPR_C, as the 30 bits are not always enough to fulfill the expectations of the original test, and the change may randomly affect the last digits. Such cases have been made explicit by testing for REPR_C or by adding a clear comment. The perf_test fft code was also missing a call to round() before casting a log_2 operation to int, which was causing a failure due to a last-decimal change. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-06-24py/obj: Fix nan handling in object REPR_C and REPR_D.Yoctopuce dev
CPython math.nan is positive with regards to copysign. The signaling bit (aka sign flag) was incorrectly set. In addition, REPR_C and REPR_D should only use the _true_ nan to prevent system crash in case of hand-crafted floats. For instance, with REPR_C, any nan-like float following the pattern `01111111 1xxxxxxx xxxxxxxx xxxxx1xx` would be switched to an immediate object or a qstr string. When the qstr index is too large, this would cause a crash. This commit fixes the issue, and adds the relevant test cases. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-06-10py/parsenum: Fix parsing complex literals with negative real part.Jeff Epler
If a complex literal had a negative real part and a positive imaginary part, it was not parsed properly because the imaginary part also came out negative. Includes a test of complex parsing, which fails without this fix. Co-authored-by: ComplexSymbol <141301057+ComplexSymbol@users.noreply.github.com> Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-05-22tests/float/math_constants.py: Test actual e and pi constant values.Damien George
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>
2025-02-28py/parsenum: Reduce code footprint of mp_parse_num_float.Yoctopuce dev
The mantissa parsing code uses a floating point variable to accumulate digits. Using an `mp_float_uint_t` variable instead and casting to `mp_float_t` at the very end reduces code size. In some cases, it also improves the rounding behaviour as extra digits are taken into account by the int-to-float conversion code. An extra test case handles the special case where mantissa overflow occurs while processing deferred trailing zeros. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2024-09-06qemu: Rename qemu-arm port to qemu.Damien George
Because this port now supports multiple architectures. Signed-off-by: Damien George <damien@micropython.org>
2024-05-28tests/float: Use "not" instead of ~ to invert bool value.Damien George
Otherwise CPython gives a deprecation warning. This test is not actually testing inversion of bools, rather that bit of the test is used to compute the pass/fail result. Signed-off-by: Damien George <damien@micropython.org>
2024-03-20tests/float/float_struct_e.py: Add specific test for struct 'e' type.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2024-03-20py/binary: Support half-float 'e' format in struct pack/unpack.Matthias Urlichs
This commit implements the 'e' half-float format: 10-bit mantissa, 5-bit exponent. It uses native _Float16 if supported by the compiler, otherwise uses custom bitshifting encoding/decoding routines. Signed-off-by: Matthias Urlichs <matthias@urlichs.de> Signed-off-by: Damien George <damien@micropython.org>
2023-12-06tests/float/inf_nan_arith.py: Include -inf in argument combos.Damien George
This adds tests for, eg, -inf + inf which should be nan. Signed-off-by: Damien George <damien@micropython.org>
2023-09-29tests/float/math_domain.py: Tweak test to also pass with obj-repr-C.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2023-09-29tests/float/float_format_ints.py: Put power-of-10 test in separate file.Damien George
This test doesn't pass on builds with 30-bit floats (object repr C). Signed-off-by: Damien George <damien@micropython.org>
2023-06-18tests/float: Test domain errors for more combos of args to math funcs.Damien George
Instead of having a special set of arguments to test for each math-module function, just test all functions with all sets of arguments. This gives improved test cases to prevent regressions. Signed-off-by: Damien George <damien@micropython.org>
2023-06-08tests: Replace umodule with module everywhere.Jim Mussared
This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2023-02-24py/modmath: Fix two-argument math function domain check.Damien George
Prior to this fix, pow(1.5, inf) and pow(0.5, -inf) (among other things) would incorrectly raise a ValueError, because the result is inf with the first argument being finite. This commit fixes this by allowing the result to be infinite if the first or second (or both) argument is infinite. This fix doesn't affect the other three math functions that have two arguments: - atan2 never returns inf, so always fails isinf(ans) - copysign returns inf only if the first argument x is inf, so will never reach the isinf(y) check - fmod never returns inf, so always fails isinf(ans) Signed-off-by: Damien George <damien@micropython.org>
2023-02-16tests/float: Make output of math function tests more readable.Damien George
By explicitly naming the function, its arguments, and result. Signed-off-by: Damien George <damien@micropython.org>
2023-02-16tests/float: Add domain checks for log and also -inf.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2023-02-09tests/float: Skip new complex tests if complex unavailable.Damien George
These complex tests were recently added. Signed-off-by: Damien George <damien@micropython.org>
2022-08-12py/formatfloat: Use pow(10, e) instead of pos/neg_pow lookup tables.Dan Ellis
Rework the conversion of floats to decimal strings so it aligns precisely with the conversion of strings to floats in parsenum.c. This is to avoid rendering 1eX as 9.99999eX-1 etc. This is achieved by removing the power- of-10 tables and using pow() to compute the exponent directly, and that's done efficiently by first estimating the power-of-10 exponent from the power-of-2 exponent in the floating-point representation. Code size is reduced by roughly 100 to 200 bytes by this commit. Signed-off-by: Dan Ellis <dan.ellis@gmail.com>
2022-07-26py/formatfloat: Format all whole-number floats exactly.Dan Ellis
Formerly, py/formatfloat would print whole numbers inaccurately with nonzero digits beyond the decimal place. This resulted from its strategy of successive scaling of the argument by 0.1 which cannot be exactly represented in floating point. The change in this commit avoids scaling until the value is smaller than 1, so all whole numbers print with zero fractional part. Fixes issue #4212. Signed-off-by: Dan Ellis dan.ellis@gmail.com
2022-07-25py/obj: Make mp_obj_get_complex_maybe call mp_obj_get_float_maybe first.Damien George
This commit simplifies mp_obj_get_complex_maybe() by first calling mp_obj_get_float_maybe() to handle the cases corresponding to floats. Only if that fails does it attempt to extra a full complex number. This reduces code size and also means that mp_obj_get_complex_maybe() now supports user-defined classes defining __float__; in particular this allows user-defined classes to be used as arguments to cmath-module function. Furthermore, complex_make_new() can now be simplified to directly call mp_obj_get_complex(), instead of mp_obj_get_complex_maybe() followed by mp_obj_get_float(). This also improves error messages from complex with an invalid argument, it now raises "can't convert <type> to complex" rather than "can't convert <type> to float". Signed-off-by: Damien George <damien@micropython.org>
2022-07-25py/obj: Add support for __float__ and __complex__ functions.Andrew Leech
2022-06-23py/parsenum: Fix parsing of complex "j" and also "nanj", "infj".Damien George
Prior to this commit, complex("j") would return 0j, and complex("nanj") would return nan+0j. This commit makes sure "j" is tested for after parsing the number (nan, inf or a decimal), and also supports the case of "j" on its own. Signed-off-by: Damien George <damien@micropython.org>
2022-06-23py/parsenum: Support parsing complex numbers of the form "a+bj".Jim Mussared
To conform with CPython. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-02-02all: Update Python formatting to latest Black version 22.1.0.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2022-01-23py/modmath: Add math.tau, math.nan and math.inf constants.stijn
Configurable by the new MICROPY_PY_MATH_CONSTANTS option.
2021-06-18tests/float: Make bytes/bytearray construct tests work with obj repr C.Damien George
2.5 can be represented correctly in object representation C, but 2.3 cannot (it is slightly truncated). Signed-off-by: Damien George <damien@micropython.org>
2021-05-26tests: Make float and framebuf tests skip or run on big-endian archs.Damien George
Signed-off-by: Damien George <damien@micropython.org>
2020-09-11py: Fix handling of NaN in certain pow implementations.stijn
Adds a new compile-time option MICROPY_PY_MATH_POW_FIX_NAN for use with toolchains that don't handle pow-of-NaN correctly.
2020-09-11py/objfloat: Fix handling of negative float to power of nan.Damien George
Prior to this commit, pow(-2, float('nan')) would return (nan+nanj), or raise an exception on targets that don't support complex numbers. This is fixed to return simply nan, as CPython does. Signed-off-by: Damien George <damien@micropython.org>
2020-09-04all: Rename "sys" module to "usys".stijn
This is consistent with the other 'micro' modules and allows implementing additional features in Python via e.g. micropython-lib's sys. Note this is a breaking change (not backwards compatible) for ports which do not enable weak links, as "import sys" must now be replaced with "import usys".
2020-08-29all: Update Python code to conform to latest black formatting.Damien George
Updating to Black v20.8b1 there are two changes that affect the code in this repository: - If there is a trailing comma in a list (eg [], () or function call) then that list is now written out with one line per element. So remove such trailing commas where the list should stay on one line. - Spaces at the start of """ doc strings are removed. Signed-off-by: Damien George <damien@micropython.org>
2020-08-29tests: Split out complex reverse-op tests to separate test file.Damien George
So they can be skipped if __rOP__'s are not supported on the target. Also fix the typo in the complex_special_methods.py filename. Signed-off-by: Damien George <damien@micropython.org>
2020-06-27py/objcomplex: Add mp_obj_get_complex_maybe for use in complex bin-op.Damien George
This allows complex binary operations to fail gracefully with unsupported operation rather than raising an exception, so that special methods work correctly. Signed-off-by: Damien George <damien@micropython.org>
2020-05-28py/modmath: Work around msvc float bugs in atan2, fmod and modf.stijn
Older implementations deal with infinity/negative zero incorrectly. This commit adds generic fixes that can be enabled by any port that needs them, along with new tests cases.
2020-04-18py/objint: Do not use fpclassify.stijn
For combinations of certain versions of glibc and gcc the definition of fpclassify always takes float as argument instead of adapting itself to float/double/long double as required by the C99 standard. At the time of writing this happens for instance for glibc 2.27 with gcc 7.5.0 when compiled with -Os and glibc 3.0.7 with gcc 9.3.0. When calling fpclassify with double as argument, as in objint.c, this results in an implicit narrowing conversion which is not really correct plus results in a warning when compiled with -Wfloat-conversion. So fix this by spelling out the logic manually.
2020-04-18tests/float: Fix cmath_fun_special for MICROPY_FLOAT_IMPL_FLOAT.stijn
When the unix and windows ports use MICROPY_FLOAT_IMPL_FLOAT instead of MICROPY_FLOAT_IMPL_DOUBLE, the test output has for example complex(-0.15052, 0.34109) instead of the expected complex(-0.15051, 0.34109). Use one decimal place less for the output printing to fix this.
2020-03-30tests/float: Add new lexer test to test parsing of float without prefix.David Lechner
Since automatically formatting tests with black, we have lost one line of code coverage. This adds an explicit test to ensure we are testing the case that is no longer covered implicitly.
2020-03-30tests: Format all Python code with black, except tests in basics subdir.David Lechner
This adds the Python files in the tests/ directory to be formatted with ./tools/codeformat.py. The basics/ subdirectory is excluded for now so we aren't changing too much at once. In a few places `# fmt: off`/`# fmt: on` was used where the code had special formatting for readability or where the test was actually testing the specific formatting.
2020-02-11tests/basics: Add tests for equality between bool and int/float/complex.Damien George
False/True should be implicitly converted to 0/1 when compared with numeric types.
2020-01-24tests: Add boolean-as-integer formatting tests for fixed regression.Yonatan Goldschmidt
As suggested by @dpgeorge in #5538.
2019-10-22tests: Rename "array" module to "uarray".Damien George
2019-08-17py/modmath: Implement math.isclose() for non-complex numbers.stijn
As per PEP 485, this function appeared in for Python 3.5. Configured via MICROPY_PY_MATH_ISCLOSE which is disabled by default, but enabled for the ports which already have MICROPY_PY_MATH_SPECIAL_FUNCTIONS enabled.
2018-09-27py/objfloat: Fix abs(-0.0) so it returns 0.0.Damien George
Nan and inf (signed and unsigned) are also handled correctly by using signbit (they were also handled correctly with "val<0", but that didn't handle -0.0 correctly). A test case is added for this behaviour.
2018-09-26py/modmath: Add math.factorial, optimised and non-opt implementations.Christopher Swenson
This commit adds the math.factorial function in two variants: - squared difference, which is faster than the naive version, relatively compact, and non-recursive; - a mildly optimised recursive version, faster than the above one. There are some more optimisations that could be done, but they tend to take more code, and more storage space. The recursive version seems like a sensible compromise. The new function is disabled by default, and uses the non-optimised version by default if it is enabled. The options are MICROPY_PY_MATH_FACTORIAL and MICROPY_OPT_MATH_FACTORIAL.
2018-09-20tests/float/float_parse.py: Add tests for accuracy of small decimals.Damien George