snap_to_grid¶
- emlib.misc.snap_to_grid(x, tick, offset=0, nearest=True)[source]¶
Find the nearest slot in a grid
Given a grid defined by offset + tick * N, find the nearest element of that grid to a given x
- Parameters:
x (
Union[float,Rational]) – the number to snap to the gridtick (
Union[float,Rational]) – distance between ticks of the gridoffset (
Union[float,Rational]) – offset of the gridnearest – if True, snap to the nearest tick (the nearest of the next floor or ceil tick), otherwise to the floor tick
- Return type:
Union[float,Rational]- Returns:
the tick to which to snap x to
Note
the result will have the same type as x, so if x is float, the result will be float, if it is a Fraction, then the result will be a fraction
Example
>>> snap_to_grid(1.6, 0.5) 1.5 >>> from fractions import Fraction >>> snap_to_grid(Fraction(2, 3), Fraction(1, 5)) Fraction(3, 5)