0

I’m trying to get a more precise result from this code:

a = str(10**20+10**-20)
b = eval(a)

I want to obtain around 42 decimal places so Python doesn’t round it to 1e+20.

  • Possible duplicate of [Limiting floats to two decimal points](https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points) – henrywongkk Oct 04 '19 at 01:54

2 Answers2

0

I used www.onlinegdb.com/online_python_compiler and got it to compile and return the correct decimal places.

pi = 3.1415926
precision = 42
print( "{:.{}f}".format( pi, precision ) )

Source: mkaz.blog/code/python-string-format-cookbook.

It seems like many, needless trailing zeros (like 10+) causes it to return iffy results for instance 10**-20 will return the correct number from a precision of 20 up to 36. After 36, the values become .000 000 000 000 000 000 009 999 etc. So if for some reason you want to return those trailing zeros, you may need to implement a way to handle those trailing zeros.

Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
Shmack
  • 1,015
  • 1
  • 11
  • 18
  • I think this method only works when you've actually got a string with a bunch of decimals already, but not when you have an expression to evaluate. – Michele Bastione Oct 04 '19 at 02:20
0

You actually 'only' need 41 to accomplish that. Use the decimal module:

import decimal
decimal.getcontext().prec=41
a = 10**20+10**decimal.Decimal(-20)

Python's floating-point types are just as inaccurate as in any other language. The decimal module contains the Decimal data structure, capable of handling arbitrarily long decimal numbers instead. You can read more about it here: check it out.

Michele Bastione
  • 333
  • 3
  • 13