You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.142253b=0.142219rtol=1e-4atol=2e-5# true because atol interferes with the rtol measurementabs(a-b) <= (atol+rtol*abs(b))
Out[24]: True# correct result, rtol failsabs(a-b) <=max(rtol*max(abs(a), abs(b)), atol)
Out[29]: False
Here is another one, this case symmetry problem:
a=0.142253b=0.142219rtol=1e-4atol=1.9776e-05# relative to babs(a-b) <= (atol+rtol*abs(b))
Out[73]: False#relative to aabs(a-b) <= (atol+rtol*abs(a))
Out[74]: True# math one has no problems with thisabs(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?
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).
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
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.
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.
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)).
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.
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.isclosedoes 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?
Reacted by Cris Luengo, Aliaksei Urbanski and Batuhan OLCAY
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?
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.
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.
importnumpyasnpfromnumpy.fftimportfft, ifftnp.random.seed(0)
x=np.random.randn(10000)*np.sqrt(2) # `mean(abs(x)) ~= 1`x[:1000] =0y=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).
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.
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:
The dtype parameter means something different in most cases. This could easily lead to confusion.
One can get the dtype from the input arguments.
My suggestion would be something along the lines of
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.
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.
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.
Activity
pv commentedon Dec 5, 2017
bashtage commentedon Dec 5, 2017
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.charris commentedon Dec 5, 2017
I confess that the current implementation looks like a bug. Note that using
max(abs(a), abs(b))instead ofabs(b)will not break any existing tests, it merely relaxes the condition in the case thatabs(a) > abs(b).eric-wieser commentedon Dec 5, 2017
At the very least, this needs a warning in the docstring that it mismatches the builtin
eric-wieser commentedon Dec 5, 2017
I don't think making this not import is possible. Just pick a longer name, like
mathlike_ufuncs, which could coverremainderas well.Note that
from __future__ import print_functionactually does produce aprint_functionglobaleric-wieser commentedon Dec 5, 2017
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 trickyeric-wieser commentedon Dec 5, 2017
You're right - and
true_divisionis obviously analogous to isclose.This is actually a nice way to avoid the problems in #9444, as an alternative to use
withstatements for managing deprecated features.njsmith commentedon Dec 6, 2017
Let's CC @ChrisBarker-NOAA as the creator of
math.isclose.This is a pretty minor issue IMO. Generally
atolandrtolare 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 thertolpart 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 thatiscloseis often called indirectly by things likeassert_allcloseor various third-party testing helpers.shoyer commentedon Dec 6, 2017
I asked on StackOverflow about using
__future__style imports: https://stackoverflow.com/questions/29905278/using-future-style-imports-for-module-specific-features-in-pythonTLDR: it's possible, but not easy or clean.
bashtage commentedon Dec 6, 2017
The other method would be to just add this as an option
isclose(...,symmetric=True)orassert_allclose(symmetric=True)where the default would beFalse, the current situation.gasparka commentedon Dec 6, 2017
I agree that this is a minor problem when you dont put a meaning to the
rtolandatolvalues, 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
rtolmeasurement is 100% (rtol * abs(b)gets close toatol, thenatol + rtol * abs(b) ~= 2 * rtol * abs(b)).Meaning that some values can pass with ~2% error:
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
isclosecore would be useful.101 remaining items
OverLordGoldDragon commentedon Aug 11, 2023
I think the following point by @ChrisBarker-NOAA isn't given remotely enough attention - that all input values are on order of unity:
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-9and2e-9is huge, yet it's invisible to NumPy.At bare minimum, this should be mentioned in
allclosedocs. At high priority, I think "the standard" for NumPy float equality should move closer tomath.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 fastallclosecan 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?
rgommers commentedon Aug 11, 2023
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).
Definitely. Would you be willing to open a PR to improve this?
OverLordGoldDragon commentedon Aug 11, 2023
Yes. Can you clarify
isclosevsallclose? Seems the PR is as simple as pasting former's note into latter, unless the two are more different than they appear.rgommers commentedon Aug 11, 2023
Yep, that looks like all that's needed there. The implementation of
allcloseis the one-linerall(isclose(...)), so they behave identically.OverLordGoldDragon commentedon Aug 12, 2023
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&atolfor lower precisions, if we can't inject it intoallclosethen I'll look into making a separate method.DOC: add warning to `allclose`, revise "Notes" in `isclose`
OverLordGoldDragon commentedon Aug 13, 2023
I'm actually not at all happy with NumPy's default
atol=1e-8with "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 most1e-15for float64.1e-8is 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-8is simply ignoring all distances below1e-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 ofaorbsince if they're "equal" it won't matter. Or safer but more compute,median(abs(a) + abs(b)) / 2e15ormedian(abs(a[a!=0])). Either way1e-15appears superior, and is much closer toatol=0.It's too late to change
atol=1e-8but not too late to simply call it a mistake in docs and advise another value. I propose the currentbe changed to
but I'll do that in a separate PR.
1e-8problem exampleArguably, vast majority cases of
allcloseseek to check whether two input-output pipelines produced the same output, rather than two sensors having gathered same data. For this,fftis an excellent prototype as it involves much addition and multiplication - but also explicitly test addition and multiplication via fractional exponentiation.So
rtolis totally ignored with defaultatol, but not proposedatol. My simpler "heuristic" in this case yieldsatol=8.2e-16.Note,
all(abs(x - y) < 1e-8)is much easier to satisfy than per above - it's not about "allclosepasses or not", it's about meeting intent. The intent is thatatolis reserved for zeros, andrtolfor 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 (egx + np.pi - np.pi).OverLordGoldDragon commentedon Aug 13, 2023
Oh. I see now that the warning is tailored toisclose, which deals with individual inputs (scalars) - no issue there. Then onlyallcloseneeds rewording, as there's room for misinterpreting "on order of 1" as meaningmean(abs(x)) ~= 1, or another aggregate measure of "size" rather than element-wise. The1e-15recommendation will only apply toallclose. 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-15is right, I confused my confusion, sorry about that.pmeier commentedon Aug 14, 2023
@OverLordGoldDragon
IIUC, you want to have a
dtypeparameter that use the value to determine the automatic tolerances in case nothing is specified? If so, I wouldn't do it like that:dtypeparameter means something different in most cases. This could easily lead to confusion.dtypefrom the input arguments.My suggestion would be something along the lines of
with
get_auto_tolerances(dtype)implementing something like #10161 (comment). This change would be fully BC and you could setdtype_specific_tolerances=Trueto get the automatic behavior.OverLordGoldDragon commentedon 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?
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'srtol&atol. We'd demote to lowest instead. Ifisclose-etc only handles 64, first demote both inputs then re-promote, information's same. I'd also prefer a shorter name for the boolean.pmeier commentedon Aug 14, 2023
Usually
dtypeis used in creation and conversion ops. And there it means "give me the result with this dtype". Here you want to usedtypeas a selector for a different parameter.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.
OverLordGoldDragon commentedon Aug 14, 2023
Ok, agreed on both, thanks for explaining.
mattip commentedon Jul 22, 2026
Closing. I don't think we will change NumPy's behaviour
math.isclose is BETTER and FASTER than numpy.isclose, see: numpy/nump…