int too large to convert to float, but even larger numbles can be handled

27 Views Asked by At

I have this function defined:

def nichtrest(n):
    return 0.9 * n**(1/4) * math.log(n)

I want to calculate this for some large numbers, e.g. n = (2 ^ 5001+1) * 2 ^ 10000 + 1.

Then I get "int too large to convert to float".

But I can run this code:

h = 2**51+1
k = 1000
n = h*2**k+1
print( n> 1)

And it says "true". So it can handle the large number n. I tried to round it down but I get the same error.

1

There are 1 best solutions below

2
Mark TeaBot On

As @Giacomo Catenazzi already mentioned, floating point numbers have a maximum value that you violate, this happens when you convert the integer to a float, by round, cast ...

See here the system information about float:

>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, 
min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, 
epsilon=2.220446049250313e-16, radix=2, rounds=1)

For the int type, see this post: Maximum and Minimum values for ints

Also the conversion to string has a limit (by print()):

Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit.

Last but not least:

The dot behind the integer generates a cast to float:

>>>a = 2 + 1.
>>> type(a)
<class 'float'>