0

I want to get large amount of accurate digits in results from divisions, such as 1/7, but Python gives different results than a high-precision calculator.

I tried the decimal library with Python 3 and tried changing its precision and rounding mode, but it gives a different result than a calculator.

from decimal import *
getcontext().prec = 40
print (Decimal(1/7))

A high-precision calculator at https://keisan.casio.com/calculator says the result is a repeating pattern of 142857, but Python's result breaks this pattern after 16 digits. Here is the number it gives:

0.142857142857142849212692681248881854116916656494140625

1 Answers1

2

You're performing the calculation with ordinary float division (1/7) and then passing that result to Decimal, so you're trying to get extra precision from something that's already approximated.

On the other hand, if you do

Decimal(1)/7

you get a more precise result:

Decimal('0.1428571428571428571428571428571428571429')
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Thank you. I went to study the rounding modes and other settings of the library, but the answer was in the first example code where they show: "Decimal(1) / Decimal(7)" Such a basic mistake. – ShootingStar91 Jan 24 '19 at 10:17