浮动四舍五入到最接近的因素? [英] Rounding float to the nearest factor?
本文介绍了浮动四舍五入到最接近的因素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小的数学问题,我试图解决
给出一个数x和分辨率Y,我需要找到下一个X'所要求的分辨率。
例如。
X = 1.002 Y = 0.1×'= 1.1
X = 0.348 Y = 0.1×'= 0.4
X = 0.50 Y = 1×= 1
X = 0.32 Y = 0.05×= 0.35
有没有在Python这样做的任何聪明的方式?
解决方案
进口数学
高清next_multiple(X,Y):
返回math.ceil(X / Y)* Y
高清try_it(X,Y):
打印X,Y,next_multiple(X,Y)
的x,y在[
(1.002,0.1),
(0.348,0.1),
(0.50,1),
(0.32,0.05)
]:
try_it(X,Y)
生产:
1.002 0.1 1.1
0.348 0.1 0.4
0.5 1 1.0
0.32 0.05 0.35
我想你的第一个例子输出是错误的,因为X'正确答案是1.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?
解决方案
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?
这篇关于浮动四舍五入到最接近的因素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文