cardinal_pythonlib.maths_py


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.


Miscellaneous mathematical functions in pure Python.

cardinal_pythonlib.maths_py.mean(values: Sequence[int | float | None]) float | None[source]

Returns the mean of a list of numbers.

Parameters:

values – values to mean, ignoring any values that are None

Returns:

the mean, or None if n = 0

cardinal_pythonlib.maths_py.n_permutations(n: int, k: int) int[source]

Returns the number of permutations of length k from a list of length n.

See https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n.

cardinal_pythonlib.maths_py.normal_round_float(x: float, dp: int = 0) float[source]

Hmpf. Shouldn’t need to have to implement this, but…

Conventional rounding to integer via the “round half away from zero” method, e.g.

1.1 -> 1
1.5 -> 2
1.6 -> 2
2.0 -> 2

-1.6 -> -2
etc.

… or the equivalent for a certain number of decimal places.

Note that round() implements “banker’s rounding”, which is never what we want: - https://stackoverflow.com/questions/33019698/how-to-properly-round-up-half-float-numbers-in-python # noqa

cardinal_pythonlib.maths_py.normal_round_int(x: float) int[source]

Version of normal_round_float() but guaranteed to return an int.

cardinal_pythonlib.maths_py.round_sf(x: float, n: int = 2) float[source]

Round to a certain number of significant figures.

As per https://code.activestate.com/lists/python-tutor/70739/, linked to from https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python

Parameters:
  • x – quantity to round

  • n – number of significant figures

Returns:

x, rounded to n significant figures

Return type:

float

This does proper rounding:

round_sf(0.55, 1)  # 0.6
round_sf(0.549, 1)  # 0.5
round_sf(-0.55, 1)  # -0.6
round_sf(-0.549, 1)  # -0.5

round_sf(0.000123456, 3)  # 0.000123
round_sf(1234567890000, 3)  # 1230000000000
round_sf(9876543210000, 3)  # 9880000000000
cardinal_pythonlib.maths_py.safe_logit(p: float | int) float | None[source]

Returns the logit (log odds) of its input probability

\alpha = logit(p) = log(x / (1 - x))

Parameters:

pp

Returns:

\alpha, or None if x is not in the range [0, 1].

cardinal_pythonlib.maths_py.sum_of_integers_in_inclusive_range(a: int, b: int) int[source]

Returns the sum of all integers in the range [a, b], i.e. from a to b inclusive.

See