Reputation: 11016
Are there data types with better precision than float?
Upvotes: 141
Views: 554427
Reputation: 363607
Python's built-in float
type has double precision (it's a C double
in CPython, a Java double
in Jython). If you need more precision, get NumPy and use its numpy.float128
.
Upvotes: 191
Reputation: 29
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
Upvotes: -3
Reputation: 65854
For some applications you can use Fraction
instead of floating-point numbers.
>>> from fractions import Fraction
>>> Fraction(1, 3**54)
Fraction(1, 58149737003040059690390169)
(For other applications, there's decimal
, as suggested out by the other responses.)
Upvotes: 23
Reputation: 1421
May be you need Decimal
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')
Upvotes: 21