Skip to content

numpy.isclose vs math.isclose #10161

Closed
Closed

Description

@gasparka

numpy.isclose (https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.isclose.html):

abs(a - b) <= (atol + rtol * abs(b))

math.isclose (https://docs.python.org/3/library/math.html#math.isclose):

abs(a - b) <= max(rtol * max(abs(a), abs(b)), atol)

Note that Numpy's equation is not symmetric and correlates the atol and rtol parameters, both are bad things (IMO).

Here is a situation where Numpy "incorrectly" flags two numbers as equal:

a = 0.142253
b = 0.142219
rtol = 1e-4
atol = 2e-5

# true because atol interferes with the rtol measurement
abs(a - b) <= (atol + rtol * abs(b))
Out[24]: True

# correct result, rtol fails
abs(a - b) <= max(rtol * max(abs(a), abs(b)), atol)
Out[29]: False

Here is another one, this case symmetry problem:

a = 0.142253
b = 0.142219
rtol = 1e-4
atol = 1.9776e-05

# relative to b
abs(a - b) <= (atol + rtol * abs(b))
Out[73]: False

#relative to a
abs(a - b) <= (atol + rtol * abs(a))
Out[74]: True

# math one has no problems with this
abs(a - b) <= max(rtol * max(abs(a), abs(b)), atol)
Out[75]: False

Python math version looks to be bulletproof, should Numpy start using this? Are there any benefits of using the Numpy version?

Activity

  1. pv commented on Dec 5, 2017

    @pv
    Member
  2. bashtage commented on Dec 5, 2017

    @bashtage
    Contributor

    This is one of the most widely used function in all of numpy (through assert_allclose) The only path for this would be to choose another name.

  3. charris commented on Dec 5, 2017

    @charris
    Member

    I confess that the current implementation looks like a bug. Note that using max(abs(a), abs(b)) instead of abs(b) will not break any existing tests, it merely relaxes the condition in the case that abs(a) > abs(b).

  4. eric-wieser commented on Dec 5, 2017

    @eric-wieser
    Member

    At the very least, this needs a warning in the docstring that it mismatches the builtin

  5. eric-wieser commented on Dec 5, 2017

    @eric-wieser
    Member

    , the import would not actually import isclose but would enable the new semantics

    I don't think making this not import is possible. Just pick a longer name, like mathlike_ufuncs, which could cover remainder as well.

    Note that from __future__ import print_function actually does produce a print_function global

  6. eric-wieser commented on Dec 5, 2017

    @eric-wieser
    Member

    Actually, the from __future__ import * style of import might not be appropriate here - in python, it affects syntax at a per-file level, and doing something similar in numpy would be tricky

  7. eric-wieser commented on Dec 5, 2017

    @eric-wieser
    Member

    You're right - and true_division is obviously analogous to isclose.

    This is actually a nice way to avoid the problems in #9444, as an alternative to use with statements for managing deprecated features.

  8. njsmith commented on Dec 6, 2017

    @njsmith
    Member

    Let's CC @ChrisBarker-NOAA as the creator of math.isclose.

    This is a pretty minor issue IMO. Generally atol and rtol are chosen by fiddling with them until tests pass, and the goal is to catch errors that are an order of magnitude larger than the tolerances. Maybe it would make sense to relax the rtol part like @charris suggested, but I really don't think it's worth pulling out stack introspection tricks for this tiny tweak. And we'd still have the problem that isclose is often called indirectly by things like assert_allclose or various third-party testing helpers.

  9. shoyer commented on Dec 6, 2017

    @shoyer
    Member
  10. bashtage commented on Dec 6, 2017

    @bashtage
    Contributor

    The other method would be to just add this as an option isclose(...,symmetric=True) or assert_allclose(symmetric=True) where the default would be False, the current situation.

  11. gasparka commented on Dec 6, 2017

    @gasparka
    Author

    I agree that this is a minor problem when you dont put a meaning to the rtol and atol values, just tune them to pass unit tests, as mentioned by @njsmith.

    However, sometimes you would like to say that the error is within, for example, 1% (rtol=0.01).
    In this case worst case error regarding rtol measurement is 100% (rtol * abs(b) gets close to atol, then atol + rtol * abs(b) ~= 2 * rtol * abs(b)).

    Meaning that some values can pass with ~2% error:

    atol = 1e-8 #default
    rtol = 0.01 # 1%
    
    b = 1e-6
    a = 1.0199e-6 # ~ 2% larger comapared to b
    abs(a - b) <= (atol + rtol * abs(b))
    True

    Implementing the idea of @charris, would make this particular case very slightly worse, as it even more relaxes the comparison, but still worth it as it gets rid of the symmetry problem and indeed is backward compatible.

    IMO it would be better if Numpy used the Math function, but i understand that the change may be too disruptive and possibly not important for most users. Making the option to change between the isclose core would be useful.

  12. 101 remaining items

  13. OverLordGoldDragon commented on Aug 11, 2023

    @OverLordGoldDragon
    Contributor

    I think the following point by @ChrisBarker-NOAA isn't given remotely enough attention - that all input values are on order of unity:

    np.allclose(1e-9, 2e-9) == True

    I do extensive numeric testing and discrete optimizations in signal processing applications, and I trusted NumPy to get this right. Filters typically rapidly decay in time and frequency domains, and that's with them being unit-normed (L1/L2, not value-by-value) - the difference between 1e-9 and 2e-9 is huge, yet it's invisible to NumPy.

    At bare minimum, this should be mentioned in allclose docs. At high priority, I think "the standard" for NumPy float equality should move closer to math.isclose - in all contexts I work with, I couldn't care less for the added compute, and accuracy is a must. I concur with back-compatibility, so the fast allclose can stay for those who want it.

    However, I see numpy.isclose does have a warning concerning the unity order. Besides that, it's just a slightly different docstring, yet the underlying formulae and default tolerances are exactly the same?

  14. rgommers commented on Aug 11, 2023

    @rgommers
    Member

    I think the following point by @ChrisBarker-NOAA isn't given remotely enough attention

    No one disagrees that this is bad. It's not about attention here, it's about doing the work needed to introduce a suitable replacement (and dealing with the high level of bike shedding that a new name is inevitably is going to attract - this is a lot more effort than you'd expect, and not much fun).

    At bare minimum, this should be mentioned in allclose docs.

    Definitely. Would you be willing to open a PR to improve this?

  15. OverLordGoldDragon commented on Aug 11, 2023

    @OverLordGoldDragon
    Contributor

    Would you be willing to open a PR to improve this?

    Yes. Can you clarify isclose vs allclose? Seems the PR is as simple as pasting former's note into latter, unless the two are more different than they appear.

  16. rgommers commented on Aug 11, 2023

    @rgommers
    Member

    Yep, that looks like all that's needed there. The implementation of allclose is the one-liner all(isclose(...)), so they behave identically.

  17. OverLordGoldDragon commented on Aug 12, 2023

    @OverLordGoldDragon
    Contributor

    What's the issue with def allclose(, dtype='float64')? Won't break any old code and will function identically.

    I'm currently looking into rtol & atol for lower precisions, if we can't inject it into allclose then I'll look into making a separate method.

  18. OverLordGoldDragon commented on Aug 13, 2023

    @OverLordGoldDragon
    Contributor

    I'm actually not at all happy with NumPy's default atol=1e-8 with "assuming on order of 1". I've done a lot of signal processing work and have a strong sense of what qualifies as "zero" for data on order of 1 - it's at most 1e-15 for float64. 1e-8 is good if you're trying to test if an individual array - a set of measurements - is close to zero, rather than for comparing two arrays which are supposed to be float-equal. 1e-8 is simply ignoring all distances below 1e-8, and there can be a ton such values (see below).

    The current heuristic I'm thinking of is atol = median(abs(x))) / 1e15 - and just settle on one of a or b since if they're "equal" it won't matter. Or safer but more compute, median(abs(a) + abs(b)) / 2e15 or median(abs(a[a!=0])). Either way 1e-15 appears superior, and is much closer to atol=0.

    It's too late to change atol=1e-8 but not too late to simply call it a mistake in docs and advise another value. I propose the current

    The default atol is not appropriate for comparing numbers that are much smaller than one (see Notes).

    be changed to

    The default atol is too large for comparing numbers that are on order of one (see Notes). 1e-15 is advised in that case.

    but I'll do that in a separate PR.

    1e-8 problem example

    Arguably, vast majority cases of allclose seek to check whether two input-output pipelines produced the same output, rather than two sensors having gathered same data. For this, fft is an excellent prototype as it involves much addition and multiplication - but also explicitly test addition and multiplication via fractional exponentiation.

    import numpy as np
    from numpy.fft import fft, ifft
    
    np.random.seed(0)
    x = np.random.randn(10000)*np.sqrt(2)  # `mean(abs(x)) ~= 1`
    x[:1000] = 0
    y = abs(ifft(fft(x))**1.15)**(1/1.15) * np.sign(x)
    y = ifft(fft(y))
    
    print(sum(abs(x - y) < 1e-8), 
          np.allclose(x, y, rtol=1e-99),
          np.allclose(x, y, atol=1e-15))  # if 1e-15 fails, so does 0
    10000 True False
    

    So rtol is totally ignored with default atol, but not proposed atol. My simpler "heuristic" in this case yields atol=8.2e-16.

    Note, all(abs(x - y) < 1e-8) is much easier to satisfy than per above - it's not about "allclose passes or not", it's about meeting intent. The intent is that atol is reserved for zeros, and rtol for all else. This intent completely fails for vast majority of cases - above computation is fairly float-intensive, and if it fails, something simpler of course also will (eg x + np.pi - np.pi).

  19. OverLordGoldDragon commented on Aug 13, 2023

    @OverLordGoldDragon
    Contributor

    Oh. I see now that the warning is tailored to isclose, which deals with individual inputs (scalars) - no issue there. Then only allclose needs rewording, as there's room for misinterpreting "on order of 1" as meaning mean(abs(x)) ~= 1, or another aggregate measure of "size" rather than element-wise. The 1e-15 recommendation will only apply to allclose. Yet this too I need to rethink, as I may have confused what I'm pointing out to be confusion - comparing array vs array and array vs scalar.

    Nope, 1e-15 is right, I confused my confusion, sorry about that.

  20. pmeier commented on Aug 14, 2023

    @pmeier

    @OverLordGoldDragon

    What's the issue with def allclose(, dtype='float64')? Won't break any old code and will function identically.

    IIUC, you want to have a dtype parameter that use the value to determine the automatic tolerances in case nothing is specified? If so, I wouldn't do it like that:

    1. The dtype parameter means something different in most cases. This could easily lead to confusion.
    2. One can get the dtype from the input arguments.

    My suggestion would be something along the lines of

    def isclose(a, b, rtol=None, atol=None, ..., dtype_specific_tolerances=False):
        if dtype_specific_tolerances and rtol is None or atol is None:
            dtype = np.promote_types(a.dtype, b.dtype)
            rtol, atol = get_auto_tolerances(dtype)
        else:
            if rtol is None:
                rtol = 1e-5
            elif atol is None:
                atol = 1e-8
    
        ...

    with get_auto_tolerances(dtype) implementing something like #10161 (comment). This change would be fully BC and you could set dtype_specific_tolerances=True to get the automatic behavior.

  21. OverLordGoldDragon commented on Aug 14, 2023

    @OverLordGoldDragon
    Contributor

    @pmeier

    The dtype parameter means something different in most cases. This could easily lead to confusion.

    I don't follow. I use NumPy a lot and I've never seen it mean anything else. What do you have in mind?

    One can get the dtype from the input arguments.

    Right, that's what I had in mind once I'd actually PR. However, I disagree with np.promote_types(a.dtype, b.dtype) - 32 & 64 -> 64, while one of inputs lacks the information necessary to pass 64's rtol & atol. We'd demote to lowest instead. If isclose-etc only handles 64, first demote both inputs then re-promote, information's same. I'd also prefer a shorter name for the boolean.

  22. pmeier commented on Aug 14, 2023

    @pmeier

    I don't follow. I use NumPy a lot and I've never seen it mean anything else. What do you have in mind?

    Usually dtype is used in creation and conversion ops. And there it means "give me the result with this dtype". Here you want to use dtype as a selector for a different parameter.

    However, I disagree with np.promote_types(a.dtype, b.dtype) - 32 & 64 -> 64, while one of inputs lacks the information necessary to pass 64's rtol & atol. We'd demote to lowest instead.

    I'm sorry, but I don't follow. Could you compile an example where you think this would be a problem?

    The idea here is to go with the more stricter tolerances by default in case the dtypes mismatch to avoid silent errors. Meaning, if you put in float32 and float64, by default it will be compared as if we had two float64. If the user didn't think about it, this operation might fail, but then they have instant feedback to change it. Either convert the float64 to float32 as well or set the tolerances manually. The other way around, we could get silent passes, which can be much worse in a testing setting.

  23. OverLordGoldDragon commented on Aug 14, 2023

    @OverLordGoldDragon
    Contributor

    Ok, agreed on both, thanks for explaining.

  24. mattip commented on Jul 22, 2026

    @mattip
    Member

    Closing. I don't think we will change NumPy's behaviour

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    57 - Close?

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions