Ayush Mishra
Ayush Mishra

Reputation: 1673

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?

Upvotes: 5

Views: 1731

Answers (3)

ironmann350
ironmann350

Reputation: 381

you can calculate any type of length float number with this function

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

Upvotes: 1

Dleep
Dleep

Reputation: 1065

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)

Upvotes: 2

Anthony Pham
Anthony Pham

Reputation: 3106

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)

Upvotes: 2

Related Questions