Skip to content

harmmean: accept negative and complex values - #518

Closed
dheerchheda77 wants to merge 1 commit into
gnu-octave:mainfrom
dheerchheda77:harmmean-negative-complex
Closed

dheerchheda77 wants to merge 1 commit into
gnu-octave:mainfrom
dheerchheda77:harmmean-negative-complex

Conversation

@dheerchheda77

Copy link
Copy Markdown

Fixes the MATLAB incompatibility reported for harmmean with negative and
complex input.

In MATLAB:

>> harmmean ([1 -1 3])
ans = 9
>> harmmean ([1 1i])
ans = 1.0000 + 1.0000i

In Octave both calls raised "harmmean: X must contain real nonnegative
values."

Cause

The input check at the top of harmmean.m rejected anything that was not
real and nonnegative. The computation below it, n ./ sum (1 ./ x), is
valid for negative and complex values on every code path (default DIM,
"all", DIM, VECDIM, "omitnan"), so only the check had to change.

Changes

  • harmmean.m: require only that X is numeric ("harmmean: X must be
    numeric."). Update the docstring, including the notes saying that a 0
    gives 0, which only holds without negative or complex values.
  • Tests: replace the error test for [1 -1 3]; add positive tests for
    negative and complex input with default DIM, "all", DIM, VECDIM and
    "omitnan", and for [1 -1] returning Inf.
  • doc-cache and NEWS updated.

Not changed

geomean has the same check, but its zero handling assumes real
nonnegative data and I have not confirmed MATLAB's behaviour for negative
input, so it is left out of this PR.

Testing

The expected values in the new tests were checked by hand and with an
independent calculation. Not yet run in Octave locally; relying on CI
for test harmmean. Still to compare against MATLAB: harmmean ([0 1i]).

  * inst/Descriptive_Statistics/harmmean.m: Only require X to be numeric,
  as MATLAB does, instead of real and nonnegative.  Update the
  documentation and the error message.  Add tests for negative and
  complex input with DIM, VECDIM, "all" and "omitnan".

  * inst/Descriptive_Statistics/doc-cache: Update the harmmean entry.

  * NEWS: Mention the change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@dheerchheda77

dheerchheda77 commented Oct 7, 2026 •

Copy link
Copy Markdown
Author

Tested locally with Octave 11.3.0 (Windows): test harmmean passes all
28 tests, and harmmean ([1 -1 3]) and harmmean ([1 1i]) now match the
MATLAB results (9 and 1 + 1i). The CI run on this PR started no jobs, so
these local results are the only test run so far.
The doc-cache entry for harmmean was updated by hand; package_texi2cache could not be checked reliably on Windows.

@dheerchheda77 dheerchheda77 closed this by deleting the head repository Oct 12, 2026
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.

1 participant