views:

384

answers:

1

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?

+11  A: 
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?

Ned Batchelder
It doesn't work for `x=0`.
J.F. Sebastian
It works for x=0 just as it works for any x that is a multiple of y: the "next" is interpreted to mean "the smallest one not smaller than", so x=0.1, y=0.1 would print 0.1. If you want "the smallest one strictly greater than", you should do "return (math.floor(x/y)+1)*y".
ShreevatsaR
Or "return math.floor(x/y+1)*y", because floor(t)+1 = floor(t+1) :-)
ShreevatsaR