小编use*_*282的帖子

在Python中'正确'舍入到小数点后3位

我可能会遗漏一些必要的东西,但是我无法找到一种方法来"正确地"在Python(2.7)中对浮点数/小数点进行舍入,至少小数点后三位.通过'正确',我的意思是1.2225应该舍入到1.223,并且1.2224应该舍入到1.222.

我知道round在设计中不能用于Python中的浮点数,但我似乎无法Decimal按预期行事,也不能按ceil功能行事.寻找内置功能而不是自定义功能变通方法,但两者都是开放的.

>>> x = 1.2225                                   # expected: 1.223
>>> round(x, 3)               
1.222                                            # incorrect

>>> from math import ceil

>>> ceil(x * 1000.0) / 1000.0
1.223                                            # correct
>>> y = 1.2224                                   # expected: 1.222
>>> ceil(y * 1000.0) / 1000.0 
1.223                                            # incorrect

>>> from decimal import Decimal, ROUND_UP, ROUND_HALF_UP

>>> x = Decimal(1.2225)
>>> x.quantize(Decimal('0.001'), ROUND_UP)
Decimal('1.223')                                 # correct
>>> y = Decimal(1.2224)
>>> y.quantize(Decimal('0.001'), ROUND_UP)
Decimal('1.223')                                 # incorrect

>>> y.quantize(Decimal('0.001'), …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

5
推荐指数
1
解决办法
2715
查看次数

递归python函数 - 无法计算边缘情况

我有以下字典:

>>> for key, details in relationships.items():
                print key, details[2]

('INVOICE', 'INVOICE') 1
('INVOICE', 'ORDER2') 0.50000000
('INVOICE', 'ORDER1') 0.01536410
('ORDER1', 'ORDER2') 0.05023163
('INVOICE', 'ORDER4') 0.00573215
('ORDER4', 'ORDER1') 0.08777898
('ORDER4', 'ORDER3') 0.01674388
Run Code Online (Sandbox Code Playgroud)

这将创建以下层次结构:

INVOICE -> ORDER2
        -> ORDER1 -> ORDER2
        -> ORDER4 -> ORDER1 -> ORDER2
                  -> ORDER3
Run Code Online (Sandbox Code Playgroud)

其中每个箭头代表的值details[2].需要计算每个订单与发票的最终"关系".预期价值:

> ORDER1: 0.01586726 (0.0153641 + 0.0877898 x 0.00573215) 
> ORDER2: 0.50079704 (0.5 + 0.05023163 x 0.0153641 + 0.05023163 x 0.0877898 x 0.00573215)
> ORDER3: 0.00009598 (0.01674388 x 0.00573215)
> ORDER4: …
Run Code Online (Sandbox Code Playgroud)

python recursion python-2.7

5
推荐指数
1
解决办法
112
查看次数

标签 统计

python ×2

python-2.7 ×2

recursion ×1