Float division of large numbers in python

I have two large numbers a

and b

are about 10000 long, for example a <= b

. Now I have to find c = a / b

, up to ten decimal places, how do I do this without losing precision?

+3


source to share


3 answers


You can use the module decimal

:



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)

      

+1


source


The module decimal

should work. As seen in the TigerhawkT3 link, you can choose the number of decimal places in which your odds 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)

      

+1


source


you can calculate any type of floating point number with this function

def longdiv(divisor,divident):
    quotient,remainder=divmod(divisor,divident)
    return (str(quotient)+str(remainder*1.0/divident)[1:])

      

+1


source







All Articles