简体   繁体   English

如何高精度地减去浮点数

[英]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.基本上我有一个数字说 5.112 我想在每次迭代中将它减去 0.001,例如 5.111、5.110、5.109、5.108 等。

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.目前,我正在考虑使用 split 方法将数字形式的小数点分开,然后将第一个索引减去 1 并加入。

I am just wondering If there is any other better way of doing this.我只是想知道是否还有其他更好的方法可以做到这一点。

Floats are imprecise (see Frank's answer and Is floating point math broken? ).浮点数是不精确的(参见Frank 的回答浮点数学是否被破坏? )。

Use decimal instead.改用decimal

from decimal import Decimal as D

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

Output:输出:

5.111
5.110
5.109
5.108
5.107

If you were to do如果你要做

x = 5.112
while True:
    x -= .001
    print(x)

You would quickly see the problems with floating point numbers and accumulating roundoff errors.您会很快看到浮点数和累积舍入误差的问题。 The easiest method to avoid this is to instead calculate 5.112 - i * .001 , where i is the number of subtractions you've performed so far.避免这种情况的最简单方法是计算5.112 - i * .001 ,其中i是您迄今为止执行的减法次数。

You can use numpy and list comprehension, like so:您可以使用 numpy 和列表​​理解,如下所示:

import numpy
start = 5.112
[start-val for val in numpy.arange(0, 0.1, 0.001)]

You just need to know how many times you want to perform this operation.您只需要知道要执行此操作的次数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM