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.
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.
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.
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.