简体   繁体   English

如何在Python中加一个浮点数?

[英]How to plus one at the tail to a float number in Python?

Is there a simple and direct way to add 'one' at float number in Python? 是否有一种简单而直接的方法可以在Python中的浮点数中添加“one”?

I mean this: 我是说这个:

if a == 0.0143:
    a = plus(a)
    assert a == 0.0144

def plus(a):
    sa = str(a)
    index = sa.find('.')
    if index<0:
        return a+1
    else:
        sb = '0'*len(sa)
        sb[index] = '.'
        sb[-1] = 1
        return a+float(sb)

This is not what I want, because it gives me 0.0144000000001. 这不是我想要的,因为它给了我0.0144000000001。

As you've noticed, not all decimal numbers can be represented exactly as floats: 正如您所注意到的,并非所有十进制数都可以完全表示为浮点数:

>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal(0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')
>>> Decimal(0.3)
Decimal('0.299999999999999988897769753748434595763683319091796875')
>>> Decimal(0.4)
Decimal('0.40000000000000002220446049250313080847263336181640625')
>>> Decimal(0.5)
Decimal('0.5')

Since you're working with the properties of decimal numbers, use the decimal module, which implements them exactly: 由于您正在使用十进制数的属性,请使用decimal模块,它完全实现它们:

from decimal import Decimal

def plus(n):
    return n + Decimal('10') ** n.as_tuple().exponent

And a demo: 还有一个演示:

>>> n = Decimal('0.1239')
>>> plus(n)
Decimal('0.1240')

You have to represent the number as a string, as representing it as a float will lose precision. 您必须将数字表示为字符串,因为将其表示为浮点将失去精度。

The downside is that using Decimal will make your plus function about 20-30 times slower than if you used floating point operations, but that's the cost of precision. 缺点是使用Decimal会使你的plus函数比使用浮点运算慢大约20-30倍,但这是精度成本。

Blender's answer is definitely a good answer, but if you insist to use floats I believe the simple way to do this is: Blender的答案肯定是一个很好的答案,但如果你坚持使用floats我相信这样做的简单方法是:

  1. Find out x for 10 ** x which can multiply your float into an integer. 找出x为10 ** x ,它可以将你的浮点数乘以整数。

  2. Add one to the enlarged number. 将一个添加到放大的数字。

  3. Divide your previous multiplier. 除以之前的乘数。

So it looks like: 所以它看起来像:

n = 0.125
e = len(str(n)) - 2
temp_n = n * 10 ** e
temp_n += 1
n = temp_n / 10 ** e
print n

EDIT: 编辑:

In the previous script, things went wrong when the number was very long. 在上一个脚本中,当数字很长时出现问题。 Results are truncated by str() and print , so I changed the script a little: 结果被str()print截断,所以我稍微更改了脚本:

n = 0.1259287345982795
e = len(repr(n)) - 2
temp_n = n * 10 ** e
temp_n += 1
n = temp_n / 10 ** e
print repr(n)
n = n + 1/10**(len(repr(n)) - 2)

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

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