simple_functions#
A collection of simple functions.
Functions
- binary_search(function, target, lower_bound, upper_bound, tolerance=0.0001)[source]#
Searches for a value in a range by repeatedly dividing the range in half.
To be more precise, performs numerical binary search to determine the input to
function
, between the bounds given, that outputstarget
to withintolerance
(default of 0.0001). ReturnsNone
if no input can be found within the bounds.Examples
Consider the polynomial \(x^2 + 3x + 1\) where we search for a target value of \(11\). An exact solution is \(x = 2\).
>>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5) >>> abs(solution - 2) < 1e-4 True >>> solution = binary_search(lambda x: x**2 + 3*x + 1, 11, 0, 5, tolerance=0.01) >>> abs(solution - 2) < 0.01 True
Searching in the interval \([0, 5]\) for a target value of \(71\) does not yield a solution:
>>> binary_search(lambda x: x**2 + 3*x + 1, 71, 0, 5) is None True
- Parameters
function (Callable[[int | float], int | float]) –
target (int | float) –
lower_bound (int | float) –
upper_bound (int | float) –
tolerance (int | float) –
- Return type
int | float | None
- choose(n, k)[source]#
The binomial coefficient n choose k.
\(\binom{n}{k}\) describes the number of possible choices of \(k\) elements from a set of \(n\) elements.
References
- Parameters
n (int) –
k (int) –
- Return type
int
- clip(a, min_a, max_a)[source]#
Clips
a
to the interval [min_a
,max_a
].Accepts any comparable objects (i.e. those that support <, >). Returns
a
if it is betweenmin_a
andmax_a
. Otherwise, whichever ofmin_a
andmax_a
is closest.Examples
>>> clip(15, 11, 20) 15 >>> clip('a', 'h', 'k') 'h'
- get_parameters(function)[source]#
Return the parameters of
function
as an ordered mapping of parameters’ names to their correspondingParameter
objects.Examples
>>> get_parameters(get_parameters) mappingproxy(OrderedDict([('function', <Parameter "function: 'Callable'">)])) >>> tuple(get_parameters(choose)) ('n', 'k')
- Parameters
function (Callable) –
- Return type
MappingProxyType[str, inspect.Parameter]