Issue
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
Solution
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))
Answered By - dogman288 Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.