代码之家  ›  专栏  ›  技术社区  ›  max

python中的负零

  •  46
  • max  · 技术社区  · 14 年前

    k = 0.0
    print(-k)
    

    输出将是 -0.0

    但是,当我比较 -k 0.0 -0.0分

    5 回复  |  直到 5 年前
        1
  •  31
  •   Michel de Ruiter    5 年前

    退房 −0 (number) in Wikipedia

    基本上,IEEE确实定义了负零。

    根据这一定义:

    -0.0 == +0.0 == 0
    

    aaronasterling 那个 -0.0 +0.0 是不同的物体。使它们相等(相等运算符)可以确保代码中不会引入细微的错误。
    想想 a * b == c * d

    >>> a = 3.4
    >>> b =4.4
    >>> c = -0.0
    >>> d = +0.0
    >>> a*c
    -0.0
    >>> b*d
    0.0
    >>> a*c == b*d
    True
    >>> 
    

    当我出于实际目的说这句话时,我已经相当仓促地选择了这个词。我是说标准的平等比较。

    +0 = -0 ,而不是 -0 < +0 . 尽管总是有可能忽略零符号,但IEEE标准并没有这样做。当乘法或除法涉及有符号零时,通常的符号规则适用于计算答案的符号。

    像这样的操作 divmod atan2 阿坦2 complies 有了IEEE的定义,底层的“C”库也一样。

    >>> divmod(-0.0,100)
    (-0.0, 0.0)
    >>> divmod(+0.0,100)
    (0.0, 0.0)
    
    >>> math.atan2(0.0, 0.0) == math.atan2(-0.0, 0.0)
    True 
    >>> math.atan2(0.0, -0.0) == math.atan2(-0.0, -0.0)
    False
    

    一种方法是通过文档找出实现是否符合IEEE行为。从讨论中还可以看出,平台也有细微的变化。

    然而,这方面(符合IEEE定义)并没有得到所有地方的尊重。看到拒绝 PEP 754 因为没有兴趣!我不确定这是不是以后拿的。

    另见 What Every Computer Scientist Should Know About Floating-Point Arithmetic

        2
  •  16
  •   Craig McQueen Dr. Watson    12 年前

    这对 atan2() 函数(至少在某些实现中)。在Windows上的Python 3.1和3.2中(根据注释,这是基于底层C实现的 CPython实现细节 靠近 bottom of the Python math module documentation ):

    >>> import math
    >>> math.atan2(0.0, 0.0)
    0.0
    >>> math.atan2(-0.0, 0.0)
    -0.0
    >>> math.atan2(0.0, -0.0)
    3.141592653589793
    >>> math.atan2(-0.0, -0.0)
    -3.141592653589793
    
        3
  •  14
  •   Alex Trebek Nabin    10 年前

    math.copysign() 对待 -0.0 +0.0 不同的是,除非您在一个奇怪的平台上运行Python:

    math. 文案 ( , 是的
    返回 带着 是的 copysign(1.0, -0.0) 回报 -1.0

    >>> import math
    >>> math.copysign(1, -0.0)
    -1.0
    >>> math.copysign(1, 0.0)
    1.0
    
        4
  •  11
  •   C. K. Young    14 年前

    是的,0.0和-0.0之间有区别(尽管Python不允许我复制它:-P)。如果你把一个正数除以0.0,你得到正无穷大;如果你把同一个数除以-0.0,你得到负无穷大。

        5
  •  1
  •   user    11 年前

    相同的值,但不同的数字

    >>> Decimal('0').compare(Decimal('-0'))        # Compare value
    Decimal('0')                                   # Represents equality
    
    >>> Decimal('0').compare_total(Decimal('-0'))  # Compare using abstract representation
    Decimal('1')                                   # Represents a > b
    


    http://docs.python.org/2/library/decimal.html#decimal.Decimal.compare http://docs.python.org/2/library/decimal.html#decimal.Decimal.compare_total