'calculating more the 19 digits of division

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?



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John
Solution 2 smichr