What is the range of values a float can have in Python?

前端 未结 6 1967
我在风中等你
我在风中等你 2020-11-29 03:43

What are its smallest and biggest values in python?

6条回答
  •  心在旅途
    2020-11-29 04:36

    Just playing around; here is an algorithmic method to find the minimum and maximum positive float, hopefully in any python implementation where float("+inf") is acceptable:

    def find_float_limits():
        """Return a tuple of min, max positive numbers
        representable by the platform's float"""
    
        # first, make sure a float's a float
        if 1.0/10*10 == 10.0:
            raise RuntimeError("Your platform's floats aren't")
    
        minimum= maximum= 1.0
        infinity= float("+inf")
    
        # first find minimum
        last_minimum= 2*minimum
        while last_minimum > minimum > 0:
            last_minimum= minimum
            minimum*= 0.5
    
        # now find maximum
        operands= []
        while maximum < infinity:
            operands.append(maximum)
            try:
                maximum*= 2
            except OverflowError:
                break
        last_maximum= maximum= 0
        while operands and maximum < infinity:
            last_maximum= maximum
            maximum+= operands.pop()
    
        return last_minimum, last_maximum
    
    if __name__ == "__main__":
        print (find_float_limits()) # python 2 and 3 friendly
    

    In my case,

    $ python so1835787.py
    (4.9406564584124654e-324, 1.7976931348623157e+308)
    

    so denormals are used.

提交回复
热议问题