0

If I want to access the 100th decimal of the number 1/919, is there a way to do so? I know that floating values are stored only upto certain decimals so I can access only the decimals which are stored but how to access the decimals which are not stored

1 Answers1

1

Your intuition is correct. Python stores floats as 64-bit floating point values, which don't have the precision to go out to 100 decimals. You will have to use the decimal package and set the precision to what you need.

import decimal

# calculate up to 120 decimals
decimal.get_context().prec = 120

result = decimal.Decimal(1) / decimal.Decimal(919)
print(result)


# pull an arbitrary digit out of the string representation of the result
def get_decimal_digit(num, index):
    # find where the decimal points start
    point = str(num).rfind('.')
    return int(str(num)[index + point + 1])

# get the 100th decimal
print(get_decimal_digit(result, 100))
dogman288
  • 613
  • 3
  • 9
  • So if I want to say access the millionth digit, I can do so? Won't this store large amount of data? – QuantumOscillator Jan 07 '21 at 09:53
  • You can if you change the precision. `decimal` uses the same idea as IEEE 754 floats of a base, sign, and exponent, they just support arbitrary precision unlike IEEE 754. So to extract the n-th digit you still have to go through the same conversion that `str()` runs. – dogman288 Jan 07 '21 at 10:02