numpy / numpy/numpy

Incorrect behavior/testing of real_if_close's "tol" argument

Open
#7,490 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
32.8k
Forks
12.8k
Avg merge
1d 7h
Merged PRs (30d)
197

Description

The docs say

    tol : float
        Tolerance in machine epsilons for the complex part of the elements
        in the array.

but

In [8]: np.real_if_close(.5j, 1)
Out[8]: array(0.0) # Oops.

Actually, the source of the issue is rather obvious in the source code:

    if tol > 1: # <--- Uh?
        from numpy.core import getlimits
        f = getlimits.finfo(a.dtype.type)
        tol = f.eps * tol

and the tests (test_type_check.py) actually cover a weird case:

        a = np.random.rand(10)
        b = real_if_close(a+1e-15j)
        assert_all(isrealobj(b))
        assert_array_equal(a, b)
        b = real_if_close(a+1e-7j)
        assert_all(iscomplexobj(b))
        b = real_if_close(a+1e-7j, tol=1e-6) # <--- Uh?
        assert_all(isrealobj(b))

I guess the writer of the test thought it was supplying a test in absolute value...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the real_if_close implementation and the existing tests in test_type_check.py, then compare the tol documentation with the reported examples. Clarify the intended tolerance semantics, update the implementation or tests accordingly, and ensure the covered cases consistently verify the documented behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
data, testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.