Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing two very large numbers in python returns 1 [duplicate]

Tags:

python

I know this question has been asked before but the solutions does not seem to be working for me. I have two very large numbers in python (2.7) like the followings:

a = 332413405639482828453084501713288536462658058395850
b = 332413405639482828453084501713288536462658058395856

and I need the result of

a/b

As you can see the there is a very tiny difference between the two so I assume the result of this division is not 0 or 1. I have tried // as suggested in other posts but that still does not return what I am looking for. Is there a solution to this or is it something impossible to do in python or with large numbers in general?

UPDATE: Btw, sorry but I forgot to mention that even by importing division from future I still do not get what I want.

Thanks

like image 561
ahajib Avatar asked May 30 '26 12:05

ahajib


1 Answers

simple floats are not precise enough, try with the Decimal module

>>> from decimal import Decimal, localcontext
>>> with localcontext() as cont:
        cont.prec=100
        Decimal(a)/Decimal(b)


Decimal('0.9999999999999999999999999999999999999999999999999819501864298840350161830097171743383579489213731828')
>>> 
like image 131
Copperfield Avatar answered Jun 02 '26 00:06

Copperfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!