Coverage for polar/kit/math.py: 31%

12 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-12-05 16:17 +0000

1import math 1ab

2from collections.abc import Iterator 1ab

3from decimal import Decimal 1ab

4 

5 

6def non_negative_running_sum(values: Iterator[int]) -> int: 1ab

7 """ 

8 Calculate the non-negative running sum of a sequence. 

9 The sum never goes below zero - if adding a value would make it negative, 

10 the sum becomes zero instead. 

11 

12 Args: 

13 values: An iterable of integers 

14 

15 Returns: 

16 The non-negative running sum 

17 """ 

18 current_sum = 0 

19 

20 for value in values: 

21 current_sum = max(0, current_sum + value) 

22 

23 return current_sum 

24 

25 

26def polar_round(number: int | float | Decimal) -> int: 1ab

27 """ 

28 Round to nearest integer, but round .5 away from 0. 

29 This means `polar_round(8.5) == 9.0` and `polar_round(-8.5) == -9.0`. 

30 

31 We can't use Python's built-in `round()` as that rounds 0.5 to 0.0. 

32 """ 

33 if number >= 0: 

34 return math.ceil(number) if number - int(number) >= 0.5 else math.floor(number) 

35 else: 

36 return math.floor(number) if number - int(number) <= -0.5 else math.ceil(number)