cardinal_pythonlib.rounding
Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Rounding functions.
Note the general need to use Decimal, not float; otherwise rounding
errors get silly, e.g. -150.1 + 0.05 == -150.04999999999998.
- cardinal_pythonlib.rounding.num_dp_from_decimal(x: Decimal, with_negative_dp: bool = False) int[source]
Return the number of decimal places used by a
Decimal.By default, this is what you’d expect; e.g.
123.45has 2 dp, and120has 0 dp. But if you setwith_negative_dptoTrue, then you if you pass in200you will get the answer-2.Beware using
str(); Decimals can look like1E+2rather than100.
- cardinal_pythonlib.rounding.range_roundable_up_to(y: int | float | Decimal, dp: int = 0, with_description: bool = False) Tuple[Decimal, Decimal] | Tuple[Decimal, Decimal, str][source]
Suppose some value
xwas rounded toywithdpdecimal places, using the “round half up” rounding method (see implementation inround_half_up()).Given
yanddp, this function finds the range[a, b), such thata <= b, within whichxmust have lain. The tuple returned isa, b.If
with_descriptionis true, the tuple returned isa, b, range_description.There are a large variety of rounding methods; see https://en.wikipedia.org/wiki/Rounding. Watch out – Python’s
round()and Numpy’snp.around()don’t do that. See https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python.Note that
dpcan be negative, as in other Python functions.
- cardinal_pythonlib.rounding.range_truncatable_to(y: int | float | Decimal, dp: int = 0, with_description: bool = False) Tuple[Decimal, Decimal] | Tuple[Decimal, Decimal, str][source]
Some value
xwas truncated toywithdpdecimal places, as per the implementation intruncate(). Return the range within whichxmust have lain.The tuple returned is
a, b, such thata <= b.If
with_descriptionis true, the tuple returned isa, b, range_description.If
yis positive, the range returned is[a, b). Ifyis negative, the range returned is(a, b].Note that
dpcan be negative, as in other Python functions.
- cardinal_pythonlib.rounding.remove_exponent_from_decimal(d: Decimal) Decimal[source]
Converts a decimal like
5.0E+3to5000. As per https://docs.python.org/3/library/decimal.html.