Search code examples
pythonnanieee-754

Why does (inf + 0j)*1 evaluate to inf + nanj?


>>> (float('inf')+0j)*1
(inf+nanj)

Why? This caused a nasty bug in my code.

Why isn't 1 the multiplicative identity, giving (inf + 0j)?


Solution

  • The 1 is converted to a complex number first, 1 + 0j, which then leads to an inf * 0 multiplication, resulting in a nan.

    (inf + 0j) * 1
    (inf + 0j) * (1 + 0j)
    inf * 1  + inf * 0j  + 0j * 1 + 0j * 0j
    #          ^ this is where it comes from
    inf  + nan j  + 0j - 0
    inf  + nan j