0

Is it possible to round a number to the nearest of a few pre defined numbers?

It would probably look something like round(x,3,6,13), where it rounds x to the nearest of the specified numbers.

So you would get:

x = 4 round(x,3,6,13) = 3

x = 7 round(x,3,6,13) = 6

x = 10 round(x,3,6,13) = 13

Bjarke Pedersen
  • 213
  • 2
  • 6
  • It is definitely possible. What have you tried? – Willem Van Onsem Oct 04 '17 at 20:08
  • you probably want the second argument to be at least a list – tipanverella Oct 04 '17 at 20:09
  • If this was numpy, you would use `np.searchsorted`. – cs95 Oct 04 '17 at 20:10
  • `np.searchsorted` is exactly what I was looking for! – Bjarke Pedersen Oct 04 '17 at 21:09
  • Wow, really? [`np.searchsorted`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html) works more like floor or ceiling rather than rounding. I mean, after using it, you still need to add your own logic to determine which of the two bounding elements is closer. (Granted, that may still be better than some of the answers in the question which this is a duplicate of.) – John Y Oct 04 '17 at 21:54

0 Answers0