Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the sqrt function of math module for long numbers in python

I was working with numbers of 200 digits in python. When finding the square root of a number using math.sqrt(n) I am getting a wrong answer.

In[1]: n=9999999999999999999999999999999999999999999999999999999999999999999999
       999999999999999999999999998292000000000000000000000000000000000000000000
       0000000000000000000000000000000000000000000000000000726067

In[2]: x=int(math.sqrt(n))

In[3]: x
Out[1]: 10000000000000000159028911097599180468360808563945281389781327
        557747838772170381060813469985856815104L

In[4]: x*x
Out[2]: 1000000000000000031805782219519836346574107361670094060730052612580
        0264077231077619856175974095677538298443892851483731336069235827852
        3336313169161345893842466001164011496325176947445331439002442530816L

In[5]: math.sqrt(n)
Out[3]: 1e+100

The value of x is coming larger than expected since x*x (201 digits) is larger than n (200 digits). What is happening here? Is there some concept I am getting wrong here? How else can I find the root of very large numbers?

like image 503
Juan John Mathews Avatar asked Dec 05 '22 04:12

Juan John Mathews


1 Answers

Using the decimal module:

import decimal
D = decimal.Decimal
n = D(99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067)

with decimal.localcontext() as ctx:
    ctx.prec = 300
    x = n.sqrt()
    print(x)
    print(x*x)
    print(n-x*x)

yields

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999145.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999983754999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998612677

99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

0E-100
like image 157
unutbu Avatar answered Dec 06 '22 19:12

unutbu