Skip to content

Complex addition/subtraction is not commutative #585

@skirpichev

Description

@skirpichev
Python 3.12.8 (Thu Oct 09 17:26:36 UTC 2025)
[Graal, Oracle GraalVM, Java 25.0.1 (amd64)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 0; y = complex(0.0,-0.0)
>>> y+x
-0j
>>> x+y
0j

It seems, this happens because specialization exists for complex+int (and complex+float) case, but not for int+complex:

abstract static class AddNode extends BinaryOpBuiltinNode {
@Specialization
static PComplex doInt(PComplex left, int right,
@Bind PythonLanguage language) {
return PFactory.createComplex(language, left.getReal() + right, left.getImag());
}
@Specialization
static PComplex doDouble(PComplex left, double right,
@Bind PythonLanguage language) {
return PFactory.createComplex(language, left.getReal() + right, left.getImag());
}

Same for subtraction:

N.B.: CPython before v3.14 had no special arithmetic rules for mixed-type operands (real values silently converted to complex type with a zero imaginary part).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions