Skip to content

fix: #3614 avoid unnecessary parentheses for complex values of a unit#3628

Open
josdejong wants to merge 1 commit intodevelopfrom
fix/3614-complex-unit-value
Open

fix: #3614 avoid unnecessary parentheses for complex values of a unit#3628
josdejong wants to merge 1 commit intodevelopfrom
fix/3614-complex-unit-value

Conversation

@josdejong
Copy link
Owner

Fixes #3614

When formatting a unit that has a complex value, parentheses are only added around the value when the value has both a non-zero real and imaginary part.

@gwhitney
Copy link
Collaborator

gwhitney commented Jan 7, 2026

You need to add a test for format on (1 + 1e-15i) kW or something like that. We want that to format to 1 kW because the complex part is negligible. But I believe it is going to fail, because you're checking if nearlyEqual(1e-15, 0), which is false, because the default abstol is 0, and reltol can't ever think something is sufficiently close to 0 in particular.

The upshot is that (currently) testing if a complex number is actually real or actually pure imaginary is tricky. My recommended method is to test if z is real via math.scalarEqual(z.re, z.re + z.im), using the mathjs function scalarEqual which in turn respects the configured tolerances. And then !math.scalarEqual(z.re, z.re+z.im) && math.scalarEqual(z.im, z.re + z.im) tests if it is pure imaginary. You need both tests because otherwise complex zero would be considered pure imaginary when in fact it is real. You can of course use equal instead of equalScalar because Unit.js already depends on equal, but the equalScalar is a bit simpler and may be slightly faster.

So perhaps actually we should add mathjs functions isReal() and isPureImaginary() so that we have an established, uniform way of testing complex numbers for these properties. You could try to push these properties back to Complex.js, but then of course that can't employ the mathjs tolerance system.

Sorry this opened a little bit of a can of worms. But I don't think this PR is ready to merge as it stands, unfortunately.

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.

Avoid unnecessary parentheses for Units with complex value when using format

2 participants