在Python中使用数学模块的sqrt函数获取长整数 [英] Using the sqrt function of math module for long numbers in python

查看:95
本文介绍了在Python中使用数学模块的sqrt函数获取长整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python中的200位数字.当使用math.sqrt(n)查找数字的平方根时,我得到了错误的答案.

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

由于x * x(201位数字)大于n(200位数字),x的值变得比预期的大.这是怎么回事这里有一些我弄错的概念吗?我还能如何找到非常大的数的根?

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?

推荐答案

math.sqrt 返回IEEE-754 64位结果,大约为17位数字.还有其他一些库可以使用高精度值.除了上面提到的 decimal mpmath 库,我还维护了 gmpy2 库(

math.sqrt returns an IEEE-754 64-bit result, which is roughly 17 digits. There are other libraries that will work with high-precision values. In addition to the decimal and mpmath libraries mentioned above, I maintain the gmpy2 library (https://code.google.com/p/gmpy/).

>>> import gmpy2
>>> n=gmpy2.mpz(99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067)
>>> gmpy2.get_context().precision=2048
>>> x=gmpy2.sqrt(n)
>>> x*x
mpfr('99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067.0',2048)
>>>

gmpy2 库还可以返回整数平方根 (isqrt) 或快速检查整数是否为精确平方 (is_square).

The gmpy2 library can also return integer square roots (isqrt) or quickly check if an integer is an exact square (is_square).

这篇关于在Python中使用数学模块的sqrt函数获取长整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆