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
being an array of floats. The numbers are rounded to the closest integer, but I want them to be rounded to the closest multiple of 2. My goal:
0.9 -> 0
1.1 -> 2
etc.
Thanks!
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.
Following is one way of doing it:
import math
data = [0.9, 1.1, 10.2, 7.4]
rounded_numbers = []
for num in data:
rounded_up_num = math.ceil(num)
if rounded_up_num % 2 == 0:
rounded_num = rounded_up_num
else:
rounded_num = math.floor(num)
rounded_numbers.append(int(rounded_num))
print rounded_numbers # [0, 2, 10, 8]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.