Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.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_Floating Point - Fatal编程技术网

Python中的浮点限制

Python中的浮点限制,python,floating-point,Python,Floating Point,我正在用python编写一个程序 import sys def func(N, M): if N == M: return 0.00 else: if M == 0: return pow(2, N+1) - 2.00 else : return 1.00 + (0.5)*func(N, M+1) + 0.5*func(N, 0) def main(*args): test

我正在用python编写一个程序

import sys

def func(N, M):
    if N == M:
        return 0.00
    else:
        if M == 0:
            return pow(2, N+1) - 2.00
        else :
            return 1.00 + (0.5)*func(N, M+1) + 0.5*func(N, 0)

def main(*args):
    test_cases = int(raw_input())
    while test_cases:
        string = raw_input()
        a = string.split(" ")
        N = int(a[0])
        M = int(a[1])
        test_cases = test_cases -1
        result = func(N, M)
        print("%.2f" % round(result, 2))

if __name__ == '__main__':
        sys.setrecursionlimit(1500)
        sys.exit(main(*sys.argv))
对于N=1000,M=1和N=1000,M=2给出了相同的答案

在搜索时,我发现浮动限制超过10^400。我的问题是如何克服它

Python中的浮点是IEEE双精度:它们不是无限精度。但是,如果您的计算只需要整数,那么只需使用整数:它们的精度是无限的。不幸的是,我认为您的计算不在整数范围内


有基于GMP的第三方软件包提供任意精度浮点:

考虑使用任意精度浮点库,例如软件包,或者。

我维护了一个Python到GMP/MPFR库,并测试了您的函数。在检查结果并查看函数之后,我认为函数仍然完全是整数。以下函数返回相同的值:

def func(N, M):
    if M == 0:
        return 2**(N+1) - 2
    elif N == M:
        return 0
    else:
        return func(N, M+1)//2 + 2**N

Python内置浮点的限制因素不是指数范围(大约10**308),而是精度(53位)。要区分func(N,1)和func(N,2),您需要大约N位的精度。

您应该修正格式:不要在代码中使用制表符,只在4个空格的缩进中使用空格。