哪个更准确,x**.5还是math.sqrt(x)?

2024-05-21 01:56:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近发现x**.5math.sqrt(x)在Python中并不总是产生相同的结果:

Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)]
on win32
>>> 8885558**.5 - math.sqrt(8885558)
-4.5474735088646412e-13

检查所有小于10**7的整数,两种方法对几乎0.1%的样本产生不同的结果,对于较大的数字,误差的大小增加(缓慢)。

所以问题是,哪种方法更准确?


Tags: 方法onbit数字整数mathsqrtdec
3条回答

两者都不准确,它们都与实际答案相等:

>>> (8885558**0.5)**2
8885557.9999999981
>>> sqrt(8885558)**2
8885558.0000000019

>>> 2**1023.99999999999
1.7976931348498497e+308

>>> (sqrt(2**1023.99999999999))**2
1.7976931348498495e+308
>>> ((2**1023.99999999999)**0.5)**2
1.7976931348498499e+308

>>> ((2**1023.99999999999)**0.5)**2 - 2**1023.99999999999
1.9958403095347198e+292
>>> (sqrt(2**1023.99999999999))**2 - 2**1023.99999999999
-1.9958403095347198e+292

http://mail.python.org/pipermail/python-list/2003-November/238546.html

The math module wraps the platform C library math functions of the same names; math.pow() is most useful if you need (or just want) high compatibility with C extensions calling C's pow().

__builtin__.pow() is the implementation of Python's infix ** operator, and deals with complex numbers, unbounded integer powers, and modular exponentiation too (the C pow() doesn't handle any of those).

**更完整。math.sqrt可能只是sqrt的C实现,它可能与pow有关。

pow函数和math.sqrt()函数都可以计算比默认浮点类型可以存储的结果更精确的结果。我认为你看到的错误是浮点数学的局限性造成的,而不是函数的不精确性。另外,当取一个7位数的平方根时,~10^(-13)的差是什么时候的问题?即使是最精确的物理计算也很少需要很多有效数字。。。

使用math.sqrt()的另一个原因是它更容易阅读和理解,这通常是以某种方式做事的好理由。

使用decimal可以找到更精确的平方根:

>>> import decimal
>>> decimal.getcontext().prec = 60
>>> decimal.Decimal(8885558).sqrt()
Decimal("2980.86531061032678789963529280900544861029083861907705317042")

相关问题 更多 >