James Harroid
James Harroid

Reputation: 107

Largest floating point number with a factor of 2

I am practising python and trying to find the largest floating point number with a factor of 2 that can be displayed by python.

I have tried the following code, however it doesn't run. Can anyone suggestion where the bug is?

a=2.
b=1.
infinity = float("inf")
while a < infinity:
    b=a*2.
    if b > infinity:
        break
    if b < infinity:
        a=b*2.
    if a > infinity:
        break

if a < infinity:
    print a
elif b < infinity:
    print b

Upvotes: 0

Views: 128

Answers (1)

Kevin
Kevin

Reputation: 76194

There is no number larger than infinity, so if b > infinity: will never be True. Try changing it to if b == infinity:, and your program will terminate as desired.


Also, you can simplify your script somewhat if you only use one variable:

a = 1.0
while True:
    if a*2 == float("inf"):
        break
    a *= 2
print a

Upvotes: 4

Related Questions