2

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

ahajib
  • 11,406
  • 26
  • 72
  • 114
  • 1
    It's not simply an issue of integer to floating point conversion. Not a direct duplicate. – svens Dec 16 '16 at 23:32

4 Answers4

9

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')
>>> 
Copperfield
  • 7,242
  • 3
  • 17
  • 26
2

Since you're in Python 2 land (and not Python 3) you're experiencing integer division. Try float(a)/float(b)

Community
  • 1
  • 1
Matt Messersmith
  • 11,503
  • 4
  • 46
  • 45
1

I believe that it is impossible to achieve what You want. Precision with this big number can't be accomplished, so result would be presented as 1 in this particular case.

We can see exact value stored in float using decimal.Decimal (according to docs):

In [1]: a = 332413405639482828453084501713288536462658058395850

In [2]: b = 332413405639482828453084501713288536462658058395856

In [3]: import decimal

In [4]: a1 = decimal.Decimal(a)

In [5]: b1 = decimal.Decimal(b)

In [6]: a1/b1
Out[6]: Decimal('1.000000000000000000000000000')
Fejs
  • 2,608
  • 2
  • 19
  • 37
0

Cast them into float first then do the division, otherwise u will get zero when the first integer is smaller than the second

Steve Deng Zishi
  • 118
  • 3
  • 10