Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal precision in python without decimal module

I'm fairly new to Python, and was wondering how would I be able to control the decimal precision of any given number without using any the decimal module or floating points (eg: " %4f" %n).

Examples (edit):

input(2/7)

0.28571428571....

input(1/3)

0.33333333333333....

and I wanted them to thousand decimal points or any decimal point for that matter. I was thinking of using a while as a controlled loop, but I'm not really sure how to do so. Thanks

edit: The reason why I'm not using the decimal module is just so I can conceptualize the algorithm/logic behind these type of things. Just trying to really understand the logic behind things.

like image 856
TTT Avatar asked Dec 16 '22 18:12

TTT


1 Answers

We can use a long to store a decimal with high precision, and do arithmetic on it. Here's how you'd print it out:

def print_decimal(val, prec):
    intp, fracp = divmod(val, 10**prec)
    print str(intp) + '.' + str(fracp).zfill(prec)

Usage:

>>> prec = 1000
>>> a = 2 * 10**prec
>>> b = a//7
>>> print_decimal(b, prec)
0.2857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857
like image 146
nneonneo Avatar answered Jan 06 '23 08:01

nneonneo