-2

I am asked to find the maximum positive number that can be supported by python. I wrote a code and got the correct answer, but then I messed a number up in the code and now I can't find what I did wrong. Can someone help me out? thanks :)

max = 1
max_precision= 1

float('inf')

while max != float('inf'):
    max = max * 10
    max_precision = max_precision + 1
print (precision)

The answer should give out 309 which is the right answer(and I got it once) but now the code keeps running endlessly and isn't giving me an answer

Bath
  • 17
  • 4

3 Answers3

3

Here you're looking for the max value an int can store. In Python3 the int type is unbounded. This means there is no real limit to the values it can store. See this excerpt from the docs:

PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.

PEP 238: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

Documentation link: https://docs.python.org/3/whatsnew/3.0.html#integers

BTables
  • 4,413
  • 2
  • 11
  • 30
0

max is initialized to 1 which is an instance of int:

>>> type(max)
<class 'int'>

When you multiply it by 10, another int, the result is an int, not a float.

Try initializing max = 1.0 instead. Including a decimal point creates a float. Multiplying a float by an int results in another float so the rest of the code works as-is.

Your final value of max_precision will be one greater than the true value because you add one even after your value goes out of range.

(It would be best to use a variable name other than max because max() is a built-in function.)

What you are really finding is the maximum n such that the value 10^n can be represented by a Python float. This is not really the "maximum positive number that can be supported by python".

You could also look at:

>>> sys.float_info.max
1.7976931348623157e+308

And if you wanted the number of digits in base 10,

>>> math.floor(math.log(sys.float_info.max)/math.log(10))+1
309
rgov
  • 3,516
  • 1
  • 31
  • 51
0

the maximum number? float do have a maximum, you can find it in the sys module, and they are system dependent if your machine is 32 or 64 bit

>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308
>>>  

int? they don't have any fix maximum, so the question here is how much ram you have... with enough of it you can calculate this for example 2**(10**100)

Copperfield
  • 8,131
  • 3
  • 23
  • 29