首页 > 解决方案 > How to substract floating point numbers with high precision

问题描述

Basically I have a number say 5.112 I want to subtract it in each iteration by 0.001 like 5.111, 5.110, 5.109, 5.108 etc.

Currently, I am thinking of using the split method to separate the number form decimal point and then subtract the 1st index by 1 and join.

I am just wondering If there is any other better way of doing this.

标签: pythonpython-3.x

解决方案


浮点数不精确(请参阅弗兰克的回答浮点数学是否损坏?)。

改为使用decimal

from decimal import Decimal as D

x = D('5.112')
mille = D('.001')
for i in range(5):
    x -= mille
    print(x)

输出:

5.111
5.110
5.109
5.108
5.107

推荐阅读