I want to make a python program that divides '1/7' in python however all I get is : 0.14285714285714285
. How can I compute more digits after the decimal?
CodePudding user response:
You should use the decimal
datatype instead of float
. It's in the standard library.
There is an example of 1/7
with specified precision at the top of the decimal docs.
CodePudding user response:
The decimal library will allow you to specify arbitrary precision. There is an example on the page here. Otherwise you could write your own code to compute the digits.
def div(a,b,n):
"""return [w,d1,d2,...dn] where a/b=w.d1d2...dn
Examples
========
>>> div(1,7,10)
[0, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8]
>>> div(10,7,4)
[1, 4, 2, 8, 5]
"""
w, r = divmod(a, b)
rv = [w]
for i in range(n):
w, r = divmod(r*10,b)
rv.append(w)
return rv