Skip to content

Show a tolerance on complex numbers #6057

Closed
@AnjoMan

Description

@AnjoMan

Suggestion

Pytest currently doesn't show tolerance when asserting approximate equality on complex numbers. This can make it a little hard to understand just how approx compares complex numbers.

for example, on pytest 5.2.2

>       assert 3.0002 + 4.0003 * 1j == approx(3 + 4j)
E       assert (3.0002+4.0003j) == (3+4j)
E         -(3.0002+4.0003j)
E         +(3+4j)

When pytest does comparisons involving complex numbers, it computes the complex different between the two numbers and then asserts that the absolute value of the difference falls below the tolerance (which, for relative tolerance is calculated as a fraction of the absolute value of the value passed to approx).

This means that if you draw a circle around the target point in the complex plane, with a radius equal to the tolerance, the compared value should fall within that circle
image

given this, I propose adding a tolerance indicator to complex numbers using a polar notation:

>       assert 3.0002 + 4.0003 * 1j == approx(3 + 4j)
E       assert (3.0002+4.0003j) == (3+4j) ± 5e-06 ∠ ±180°
E         -(3.0002+4.0003j)
E         +(3+4j) ± 5e-06 ∠ ±180°

in this notation, 5e-06 is the calculated relative tolerance, derived as abs(3+4j) * 1e-06. the ∠ ±180° component is fixed to indicate that the delta between actual and expected is a complex value as well, and that it can have any angle as long as the magnitude is within the tolerance.

Version

* pytest 5.2.2
* python 3.7.3
* ubuntu 19.04

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