简体   繁体   English

有什么办法可以增加蟒蛇的无限极限吗?

[英]Is there any way to increase pythons infinity limit?

I am doing https://projecteuler.net/problem=57 where I get the numerator and the denominator and if the numerator is longer than the denominator I add one to the total.我正在做https://projecteuler.net/problem=57我得到分子和分母,如果分子长于分母,我在总数中加一。

However, at one point (above n=805) the numerator and denominator get so large, that python converts them to infinity.然而,在某一时刻(在 n=805 以上),分子和分母变得如此之大,以至于 python 将它们转换为无穷大。 Here is my code if you want to test it.如果你想测试它,这是我的代码。

def sqrt_2(max_iteration, total = 0, previous_numerator = 1, previous_denominator = 2, iteration = 1):
    
    numerator_test = previous_numerator + previous_denominator
    denominator_test = previous_denominator
    print(numerator_test, denominator_test, numerator_test / denominator_test)
    if len(str(numerator_test)) > len(str(denominator_test)):
        total += 1
    
    if iteration == max_iteration:
        return total
    
    next_value_numerator = 1 * previous_denominator
    next_value_denominator = int(( 2 + (previous_numerator / previous_denominator) ) * previous_denominator)
    
    return sqrt_2(max_iteration, total, next_value_numerator, next_value_denominator, iteration + 1)
            


print("\n", sqrt_2(806))

Is there any way to increase this infinity limit?有什么办法可以增加这个无穷大吗? 806 is really quite close to 1000. If it has anything to do with the IDE / Python version, I'm using Spyder 5.0 and python 3.7. 806真的很接近1000。如果和IDE / Python版本有什么关系,我用的是Spyder 5.0和Z23EEEB4347BDD756BFC6B7EE9A33

Thanks in advance!提前致谢!

You cannot use floating-point arithmetic here.您不能在此处使用浮点运算。 Floating point supports a limited number of significant digits (17 or some such).浮点支持有限数量的有效数字(17 或一些这样的数字)。 When the code divides numbers, the result is a floating-point number, and very soon (iteration 25 or some such) there will be not enough precision to represent it as float .当代码除以数字时,结果是一个浮点数,很快(迭代 25 次或类似的迭代)将没有足够的精度将其表示为float

What actually happens is your numbers become so large, float cannot even represent their exponent, and overflows to infinity.实际发生的是你的数字变得如此之大, float甚至不能代表它们的指数,并且溢出到无穷大。 But that shouldn't matter, because the numbers are wrong long before they overflow.但这不重要,因为数字在溢出之前很久就错了。

What you need is an algorithm which calculates numerator and denominator using only integer operations (like addition and multiplication), no division.您需要的是一种算法,它只使用 integer 运算(如加法和乘法)计算分子和分母,没有除法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM