哪个更准确,x **。5或math.sqrt(x)? [英] Which is more accurate, x**.5 or math.sqrt(x)?

查看:127
本文介绍了哪个更准确,x **。5或math.sqrt(x)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

检查10 ** 7以下的所有整数,这两种方法产生的结果几乎完全是样本的0.1%,误差的大小随着数量的增加(缓慢)而增加。

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

两者都不是更准确,实际答案在同等部分:

 >>> (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


数学模块包装平台C
同一个
名字的图书馆数学函数; math.pow()如果
您需要(或者只是想要)高
兼容C扩展
调用C <$ code> pow()。



__ builtin __。pow()执行Python的中缀 **
运算符,并且处理复数
数字,无限整数幂和
模幂运算(C
pow()不处理任何这些内容)。



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


I recently discovered that x**.5 and math.sqrt(x) do not always produce the same result in 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

Checking all integers below 10**7, the two methods produced different results for almost exactly 0.1% of the samples, with the size of the error increasing (slowly) for larger numbers.

So the question is, which method is more accurate?

解决方案

Neither one is more accurate, they both diverge from the actual answer in equal parts:

>>> (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).

** is more complete. math.sqrt is probably just the C implementation of sqrt which is probably related to pow.

这篇关于哪个更准确,x **。5或math.sqrt(x)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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