Skip to content

Handle negative imaginary parts in number_to_string (#551)#598

Open
koriyoshi2041 wants to merge 1 commit into
qlustered:masterfrom
koriyoshi2041:fix/number-to-string-negative-imaginary
Open

Handle negative imaginary parts in number_to_string (#551)#598
koriyoshi2041 wants to merge 1 commit into
qlustered:masterfrom
koriyoshi2041:fix/number-to-string-negative-imaginary

Conversation

@koriyoshi2041
Copy link
Copy Markdown

Fixes #551.

number_to_string reconstructs complex numbers by formatting then re-parsing:

number = number.__class__(
    "{real}+{imag}j".format(real=..., imag=...)
)

When the imaginary part is negative, the formatted imag already starts with -, so the literal + produces an invalid string such as "1.0+-1.0j", and complex("1.0+-1.0j") raises ValueError: complex() arg is a malformed string.

>>> from deepdiff.helper import number_to_string
>>> number_to_string(1-1j, significant_digits=1)
ValueError: complex() arg is a malformed string
>>> from deepdiff import DeepHash
>>> DeepHash(1-1j, significant_digits=3)   # same crash

The fix joins real and imag using the imaginary part's own sign, so negative imaginary parts produce "1.0-1.0j" instead of "1.0+-1.0j". Positive parts are unchanged.

The existing test_number_to_string_complex_digits cases only exercised non-negative (or rounds-to-zero) imaginary parts. Added two cases with non-zero negative imaginary parts (which raised before the fix); the full parametrized test passes.

number_to_string rebuilt complex numbers via "{real}+{imag}j".format(...).
When the imaginary part is negative this produced an invalid string like
"1.0+-1.0j", and the complex() round-trip raised ValueError -- so
number_to_string(1-1j) and, by extension, DeepHash(1-1j, significant_digits=3)
crashed. Join using the imaginary part's own sign instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Common ValueError raised when formatting complex numbers

1 participant