Skip to content
Advertisement

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.

However, at one point (above n=805) the numerator and denominator get so large, that python converts them to infinity. 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.

Thanks in advance!

Advertisement

Answer

You cannot use floating-point arithmetic here. Floating point supports a limited number of significant digits (17 or some such). 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.

What actually happens is your numbers become so large, float cannot even represent their exponent, and overflows to infinity. 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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement