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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With