Wiz123
Wiz123

Reputation: 920

Rounding up to two limits in Python

I am trying to round up to nearest 10 for Max and Min. However, for Max, the nearest 10 should be greater than Max and for Min, the nearest 10 should be less than Min. The current and the expected outputs are presented.

import numpy as np
Max = [99.91540553]
Min = [8.87895014]
Amax=round(Max[0],-1)
Amin=round(Min[0],-1)

The current output is

Amax=100
Amin=10.0

The expected output is

Amax=100
Amin=0.0

Upvotes: 1

Views: 56

Answers (2)

snoopyhunter
snoopyhunter

Reputation: 95

If I understand your question correctly, you'd need the floor and ceil functions from the math module.

import math as m
Max = [99.91540553]
Min = [8.87895014]
Amax = 10*m.ceil(Max[0]/10)
Amin = 10*m.floor(Min[0]/10)

These also exist in numpy if you would like to perform this on every element in a numpy array:

import numpy as np
Max = np.array([99.91540553, 95.7, 93.2])
Min = np.array([8.87895014, 15.7, 17.2])
Amax = 10*np.ceil(Max/10)
Amin = 10*np.floor(Min/10)

Upvotes: 2

Leonardo Boscolo
Leonardo Boscolo

Reputation: 467

You can use math.floor and math.ceil, these functions round only to units so we just divide by ten and then multiply by ten to round to tens.

import math
Max = [99.91540553]
Min = [8.87895014]
Amax= 10*math.ceil(Max[0]/10)
Amin= 10*math.floor(Min[0]/10)
print(Amax, Amin)

Output

100 0

Upvotes: 2

Related Questions