The following behaviour is desired, for a scalar x
round to the nearest value of y
. Consider the following example:
>>> x = [0.00203, 0.5205, 0.78, 1.2323789374]
>>> z = round_up_to_nearest(x, 0.2)
>>> print(z)
[0.2, 0.6, 0.8, 1.4]
To my surprise there was not an existing function for this, so I came up with the following:
def round_up_to_nearest(x, y=0.1):
"""Round scalar x up to float y as nearest"""
return np.ceil(x / y) * y
This has an issue with floating point precision, for example in the following case:
>>> round_up_to_nearest(1.523495812734345,0.273)
1.6380000000000001
Where the desired output is 1.638
.
To overcome this I thought of rounding the output to the number of d.p. specified in y
as follows:
def round_up_to_nearest(x, y=0.1):
"""Round scalar x up to float y as nearest"""
return np.round(np.ceil(x / y) * y, decimals=len(str(y).split('.')[1]))
Which then returns the desired output:
>>> round_up_to_nearest(1.523495812734345,0.273)
1.638
However, this solution seems overly complex, not readable and is not performant given I need to apply this millions of times. Is there a more optimised solution?