Python arithmetic with small numbers

前端 未结 7 1311
面向向阳花
面向向阳花 2021-01-18 00:59

I am getting the following unexpected result when I do arithmetic with small numbers in Python:

>>> sys.float_info
sys.float_info(max=1.797693134862         


        
7条回答
  •  自闭症患者
    2021-01-18 01:44

    If you need this level of precision, consider the Decimal module

    >>> decimal.Decimal(1.0)-decimal.Decimal('1.0e-17')
    Decimal('0.999999999999999990')
    >>> decimal.Decimal(1.0)-decimal.Decimal('1.0e-17')

    And:

    >>> decimal.Decimal(1.0)-decimal.Decimal('1.0e-17')<1.0
    True
    

    Careful with the last one though because you can get conversion errors.

    Others have suggested What Every Computer Scientist Should Know About Floating-Point Arithmetic. and I also recommend Don’t Store That in a Float

提交回复
热议问题