Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float division of big numbers in python

I have two big numbers a and b of length around 10000, such that a <= b. Now, I have to find c = a / b, upto 10 places of decimal, how do I do it without loosing precision?

like image 697
Ayush Mishra Avatar asked Jul 08 '15 23:07

Ayush Mishra


2 Answers

The decimal module should work. As seen in TigerhawkT3's link, you can choose the number of decimal places your quotient should be.

from decimal import *
getcontext().prec = 6
a = float(raw_input('The first number:'))       #Can be int() if needed
b = float(raw_input('The second number:'))
c = Decimal(a) / Decimal(b)
print float(c)
like image 71
Anthony Pham Avatar answered Oct 31 '22 11:10

Anthony Pham


You could use the decimal module:

from decimal import localcontext, Decimal

def foo(a, b):
    with localcontext() as ctx:
        ctx.prec = 10   # Sets precision to 10 places temporarily
        c = Decimal(a) / Decimal(b) # Not sure if this is precise if a and b are floats, 
                                    # str(a) and str(b) instead'd ensure precision i think.
    return float(c)
like image 43
Dleep Avatar answered Oct 31 '22 11:10

Dleep