Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:任意精度_Python - Fatal编程技术网

python:任意精度

python:任意精度,python,Python,我试着编写一个简单的程序,以正常精度计算函数的导数: # second derivative of a function def diff2(f, x, h=1E-6): r = (f(x-h) - 2*f(x) + f(x+h))/float(h*h) return r # define the function to derivate def g(t): return t**(-6) # decresing h increasing the

我试着编写一个简单的程序,以正常精度计算函数的导数:

# second derivative of a function
def diff2(f, x, h=1E-6):
        r = (f(x-h) - 2*f(x) + f(x+h))/float(h*h)
        return r

# define the function to derivate
def g(t):
        return t**(-6)

# decresing h increasing the precision of the derivative
# ROUND-OFF problems are present
for k in range(1,15):
        h = 10**(-k) # 15 different value of h
        d2g = diff2(g, 1, h) # compute d'' of g 15-th times in point t=1
        print 'h=%.0e: %.5f' % (h, d2g)
从打印操作中可以看出,由于舍入,当k大于8时,我有问题。我知道我可以使用:

从十进制导入*

但我不知道如何在我的功能中实现这些命令


有人能帮我吗?

如果你想在x_0位置求导数,并用浮点数进行计算,
h
的最佳值是
sqrt(sys.float\u info.epsilon)*x_0
,对于
x_0=1
的情况,该值约为1E-8


有关更多信息和该值的推导,请参见第4页至中结束的章节
如何选择h

值得研究python模块,它可以处理任意精度。例如:

>>> from mpmath import mp
>>> mp.dps = 50
>>> print(mp.quad(lambda x: mp.exp(-x**2), [-mp.inf, mp.inf]) ** 2)
3.1415926535897932384626433832795028841971693993751

您可以简单地更改类型,让函数以更高的精度工作。值得注意的是@halex的注释和答案。

您可以使用十进制模块:

from decimal import Decimal

# second derivative of a function
def diff2(f, x, h=1E-6):
    x, h = Decimal(x), Decimal(h)
    r = (f(x - h) - 2 * f(x) + f(x + h)) / Decimal(h * h)
    return r