Jua*_*ews 4 python long-integer
我正在使用python中的200位数字.当使用math.sqrt(n)找到数字的平方根时,我得到了错误的答案.
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
Run Code Online (Sandbox Code Playgroud)
由于x*x(201位)大于n(200位),因此x的值大于预期值.这里发生了什么?是否有一些概念我在这里错了?我怎么能找到大数字的根?
math.sqrt返回一个IEEE-754 64位结果,大约是17位数.还有其他库可以使用高精度值.除了上面提到的库decimal和mpmath库,我还维护了gmpy2库(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)
>>>
Run Code Online (Sandbox Code Playgroud)
该gmpy2库还可以返回整数平方根(isqrt)或快速检查整数是否是精确的平方(is_square).
使用十进制模块:
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)
Run Code Online (Sandbox Code Playgroud)
产量
9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999145.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999983754999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998612677
99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999982920000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000726067.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0E-100
Run Code Online (Sandbox Code Playgroud)