浮动四舍五入到最接近的因素?最接近、因素、四舍五入

2023-09-11 05:40:39 作者:国妓总奸

我有一个小的数学问题,我试图解决

给出一个数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
 
20个不常见但是却非常有用的Numpy函数

我想你的第一个例子输出是错误的,因为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?

 
精彩推荐
图片推荐