py/parsenum.c: reduce code footprint of mp_parse_num_float. #16672
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
The existing 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 is more efficient and 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.
Testing
The new code was unit-tested using a small program generating 100'000 random mantissa and exponents, parsing the resulting number as a float and comparing the result to the value obtained via bigint arithmetic.
MICROPY_FLOAT_IMPL_DOUBLE
, with exponents between -200 and 200MICROPY_FLOAT_IMPL_FLOAT
, with exponents between -20 and 50The code size reduction was observed on binaries built using gcc-arm-none-eabi-9-2019-q4-major
Trade-offs and Alternatives
A further improvement in precision for positive exponents could be obtained by leveraging bigint arithmetic up to the computation of the final value:
This would however increase the code size, and cause dynamic object allocation in case the mantissa is larger then 9 digits or the absolute value of the exponent is bigger than 9, so this idea was dropped.