0

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?

Him
  • 5,257
  • 3
  • 26
  • 83
William Grimes
  • 675
  • 2
  • 11
  • 29
  • 1
    The earlier question is helpful but this question is different in that I want to round up any scalar, to the nearest `y` not just decimal place, but `y` could be 0.01 or 5. And I'm asking about the performance of such an operation. The earlier link does not help me in doing this – William Grimes May 07 '19 at 08:33
  • I agree with the OP. I am curious about this functionality, and the supposed duplicate does not address this problem. – Him Sep 30 '19 at 16:19
  • @tripleee, note that the supposed duplicate only allows one to round to even powers of 10. The OP would like to round to arbitrary quantities, and specifically points out how rounding to even powers of 10 is a non-solution (which is the problem that the supposed dupe solves). – Him Sep 30 '19 at 18:29

0 Answers0