Skip to content

Commit 7475117

Browse files
committed
-
1 parent 8ac963c commit 7475117

File tree

1 file changed

+37
-17
lines changed
  • source_py3/python_toolbox/math_tools

1 file changed

+37
-17
lines changed

source_py3/python_toolbox/math_tools/misc.py

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -165,28 +165,48 @@ class RoundMode(python_toolbox.cute_enum.CuteEnum):
165165

166166
def cute_round(x, round_mode=RoundMode.CLOSEST_OR_DOWN, *, step=1):
167167
'''
168-
Round with a chosen step.
168+
Round a number, with lots of different options for rounding.
169169
170-
Examples:
171-
blocktododoc explain the different options, especially probabilistic
170+
Basic usage:
171+
172172
>>> cute_round(7.456)
173173
7
174-
>>> cute_round(7.456, up=True)
175-
8
176-
>>> cute_round(7.456, step=0.1)
177-
7.4
178-
>>> cute_round(7.456, step=0.1, up=True)
179-
7.5
180-
>>> cute_round(7.456, step=0.2)
181-
7.4
182-
>>> cute_round(7.456, step=0.2, up=True)
183-
7.6
184-
>>> cute_round(7.456, step=0.01)
185-
7.45
186-
>>> cute_round(7.456, step=0.01, up=True)
187-
7.46
174+
175+
The optional `step=1` argument can be changed to change the definition of a
176+
round number. e.g., if you set `step=100`, then 1234 will be rounded to
177+
1200. `step` doesn't have to be an integer.
178+
179+
There are different rounding modes:
180+
181+
RoundMode.CLOSEST_OR_DOWN
182+
183+
Default mode: Round to the closest round number. If we're smack in
184+
the middle, like 4.5, round down to 4.
185+
186+
RoundMode.CLOSEST_OR_UP
187+
188+
Round to the closest round number. If we're smack in the middle,
189+
like 4.5, round up to 5.
190+
191+
RoundMode.ALWAYS_DOWN
192+
193+
Always round down. Even 4.99 gets rounded down to 4.
194+
195+
RoundMode.ALWAYS_UP
196+
197+
Always round up. Even 4.01 gets rounded up to 5.
198+
199+
RoundMode.PROBABILISTIC
200+
201+
Probabilistic round, giving a random result depending on how close
202+
the number is to each of the two surrounding round numbers. For
203+
example, if you round 4.5 with this mode, you'll get either 4 or 5
204+
with an equal probability. If you'll round 4.1 with this mode,
205+
there's a 90% chance you'll get 4, and a 10% chance you'll get 5.
206+
188207
189208
'''
209+
assert step > 0
190210
div, mod = divmod(x, step)
191211
if round_mode == RoundMode.CLOSEST_OR_DOWN:
192212
round_up = (mod > 0.5 * step)

0 commit comments

Comments
 (0)