I have a small math problem I am trying to solve
Given a number x and resolution y, I need to find the next x' with the required resolution.
e.g.
x = 1.002 y = 0.1 x'= 1.1
x = 0.348 y = 0.1 x'= 0.4
x = 0.50 y = 1 x'= 1
x = 0.32 y = 0.05 x'= 0.35
Is there any smart way of doing this in Python?
In floating point arithmetic, two extra bits are used to the far right of the significand, called the guard and round bits. At the end of the arithmetic calculation, these bits are rounded off. We always round towards the closer digit (i.e. 0.00-‐0.49 → 0 and 0.51-‐0.99 → 1).
Float number always round up.
In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
Rounding to the nearest integer is really rounding to the nearest units place. Sometimes, you will be asked to round to the nearest hundreds, or to the nearest hundredths — to some decimal place other than the units place. The rule is just a more generalized version of the previous rounding rule.
import math
def next_multiple(x, y):
return math.ceil(x/y)*y
def try_it(x, y):
print x, y, next_multiple(x, y)
for x, y in [
(1.002, 0.1),
(0.348, 0.1),
(0.50, 1),
(0.32, 0.05)
]:
try_it(x, y)
produces:
1.002 0.1 1.1
0.348 0.1 0.4
0.5 1 1.0
0.32 0.05 0.35
I think your first example output is wrong, The correct answer for x' is 1.1, right?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With