Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding float to the nearest factor?

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?

like image 548
coulix Avatar asked Dec 07 '08 12:12

coulix


People also ask

How do you round a floating point?

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).

Does float round up or down?

Float number always round up.

Does float round up in C?

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).

What does it mean to round to 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.


1 Answers

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?

like image 145
Ned Batchelder Avatar answered Oct 08 '22 01:10

Ned Batchelder