Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

Is there a simple and direct way to add 'one' at float number in Python?

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.

like image 951
user2003548 Avatar asked Aug 07 '13 01:08

user2003548


People also ask

How do you assign a float value in Python?

The float() method is a built-in Python function that is used to convert an integer or a string to a floating-point value. The float() method takes in one parameter: the value you want to convert to a float. This parameter is optional and its default value is 0.0.


1 Answers

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:

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.

like image 106
Blender Avatar answered Oct 24 '22 22:10

Blender