jstack - 1 year ago 70

Python Question

to further explain my title: I have an array of floats which I want to round, HOWEVER, I want to round the numbers to a number that isn't the closest integer. For example, let's say I want the numbers to be rounded to the nearest integer that is a multiple of 2. This is what I have:

`Temp = np.around(data,0)`

with

`data`

0.9 -> 0

1.1 -> 2

etc.

Thanks!

Answer Source

A multiple of two is straightforward:

```
x = np.array([0.9, 1.1, 10.2, 7.4])
2*np.round(x/2) # array([ 0., 2., 10., 8.])
```

But there's not a universal approach to this. For example there's no obvoius "round to the nearest Fibonacci number". Consider the formula for multiple of `2`

as, given a function `f(x)=2*x`

: 1) first apply the inverse of `f`

(divide in this case), 2) then `round`

, 3) then apply `f`

to result. For this to work, `f`

must exist, have an inverse, and the result must also be an `int`

; so it only works for a few functions.