我如何才能获得一个浮动变量,并控制浮点数在不带圆形()的情况下走多远?例如。
w = float(1.678)我想取x,然后用它做下面的变量。
x = 1.67
y = 1.6
z = 1如果我使用各自的圆方法:
x = round(w, 2) # With round I get 1.68
y = round(y, 1) # With round I get 1.7
z = round(z, 0) # With round I get 2.0它将使数字四舍五入,使之对我毫无用处。我知道这是关键所在,它的运作也是正常的。我如何获得x,y,z变量中所需的信息,并且仍然能够以浮点格式在其他方程中使用这些信息?
发布于 2015-03-25 14:00:15
你可以:
def truncate(f, n):
return math.floor(f * 10 ** n) / 10 ** n测试:
>>> f=1.923328437452
>>> [truncate(f, n) for n in range(7)]
[1.0, 1.9, 1.92, 1.923, 1.9233, 1.92332, 1.923328]发布于 2015-03-25 03:01:35
一个超级简单的解决方案是使用字符串。
x = float (str (w)[:-1])
y = float (str (w)[:-2])
z = float (str (w)[:-3])任何浮点库解决方案都需要你回避一些四舍五入,并且使用10的地板/幂来挑选小数可以得到一些毛茸茸的与上面的相比。
发布于 2020-02-06 21:15:36
整数比浮动/双倍(比字符串更快)操作更快。在本例中,我试图为这两种方法争取时间:
timeit.timeit(stmt = "float(str(math.pi)[:12])", setup = "import math", number = 1000000)~1.1929605630000424
适用于:
timeit.timeit(stmt = "math.floor(math.pi * 10 ** 10) / 10 ** 10", setup = "import math", number = 1000000)~0.3455968870000561
因此,使用math.floor而不是对其进行字符串操作是安全的。
https://stackoverflow.com/questions/29246455
复制相似问题