Are there data types with better precision than float?
-
6This is actually two questions with different answers. 1: double precision values in python are floats, and 2: a better precision data type than float would be decimal. Can questions like this be split somehow? The accepted answer addresses #2, but most upvoted answer addresses #1.bsplosion– bsplosion2019-03-15 14:30:14 +00:00Commented Mar 15, 2019 at 14:30
5 Answers
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.
7 Comments
numpy.float128 often has 64 bit precision on a 64 bit system. numpy.float128(1) + numpy.float128(2**-64) - numpy.float128(1) returns 0.0. See stackoverflow.com/a/29821557/420755- Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem.
If you are pressed by performance issuses, have a look at GMPY
3 Comments
float-s are double precision"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.)
3 Comments
Decimal when you want to work with approximate numbers that have fixed (but configurable) precision. Use Fraction when you want to work with exact ratios, and are prepared to put up with their unbounded storage requirements.May be you need Decimal
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')
Comments
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)
3 Comments
numpy.floor(100*a)/100 to truncate a number a to two decimal places.