Double precision smooth values โ€‹โ€‹in Python?

Are data types more accurate than float?

+47
python types precision
Jul 12 '11 at 11:09
source share
5 answers

Decimal data type

  • Unlike the hardware binary floating point, the decimal module has user-adjustable accuracy (28 places by default), which can be as large as required for this problem.

If you clicked on performance features, check out GMPY

+31
Jul 12 '11 at 11:11
source share

Python's built-in float has double precision (it's C double in CPython, Java double in Jython). If you need higher accuracy, get NumPy and use it numpy.float128 .

+72
Jul 12 '11 at 11:11
source share

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 is decimal , as suggested by other answers.)

+11
Jul 12 '11 at 11:16
source share

You may need a decimal

 >>> from decimal import Decimal >>> Decimal(2.675) Decimal('2.67499999999999982236431605997495353221893310546875') 

Floating point arithmetic

+9
Jul 12 '11 at 11:15
source share

Here is my solution. First, I create random numbers with random.uniform, format them into a double precision string, and then convert them back to float. You can adjust the accuracy 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) 
0
Mar 31 '15 at 11:31
source share



All Articles