numpy.testing.assert_allclose#
- testing.assert_allclose(actual,desired,rtol=1e-07,atol=0,equal_nan=True,err_msg='',verbose=True,*,strict=False)[source]#
Raises an AssertionError if two objects are not equal up to desiredtolerance.
Given two array_like objects, check that their shapes and all elementsare equal (but see the Notes for the special handling of a scalar). Anexception is raised if the shapes mismatch or any values conflict. Incontrast to the standard usage in numpy, NaNs are compared like numbers,no assertion is raised if both objects have NaNs in the same positions.
The test is equivalent to
allclose(actual,desired,rtol,atol)(notethatallclosehas different default values). It compares the differencebetweenactual anddesired toatol+rtol*abs(desired).- Parameters:
- actualarray_like
Array obtained.
- desiredarray_like
Array desired.
- rtolfloat, optional
Relative tolerance.
- atolfloat, optional
Absolute tolerance.
- equal_nanbool, optional.
If True, NaNs will compare equal.
- err_msgstr, optional
The error message to be printed in case of failure.
- verbosebool, optional
If True, the conflicting values are appended to the error message.
- strictbool, optional
If True, raise an
AssertionErrorwhen either the shape or the datatype of the arguments does not match. The special handling of scalarsmentioned in the Notes section is disabled.New in version 2.0.0.
- Raises:
- AssertionError
If actual and desired are not equal up to specified precision.
Notes
When one ofactual anddesired is a scalar and the other isarray_like, the function performs the comparison as if the scalar werebroadcasted to the shape of the array.This behaviour can be disabled with thestrict parameter.
Examples
>>>x=[1e-5,1e-3,1e-1]>>>y=np.arccos(np.cos(x))>>>np.testing.assert_allclose(x,y,rtol=1e-5,atol=0)
As mentioned in the Notes section,
assert_allclosehas specialhandling for scalars. Here, the test checks that the value ofnumpy.sinis nearly zero at integer multiples of π.>>>x=np.arange(3)*np.pi>>>np.testing.assert_allclose(np.sin(x),0,atol=1e-15)
Usestrict to raise an
AssertionErrorwhen comparing an arraywith one or more dimensions against a scalar.>>>np.testing.assert_allclose(np.sin(x),0,atol=1e-15,strict=True)Traceback (most recent call last):...AssertionError:Not equal to tolerance rtol=1e-07, atol=1e-15(shapes (3,), () mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array(0)
Thestrict parameter also ensures that the array data types match:
>>>y=np.zeros(3,dtype=np.float32)>>>np.testing.assert_allclose(np.sin(x),y,atol=1e-15,strict=True)Traceback (most recent call last):...AssertionError:Not equal to tolerance rtol=1e-07, atol=1e-15(dtypes float64, float32 mismatch) ACTUAL: array([ 0.000000e+00, 1.224647e-16, -2.449294e-16]) DESIRED: array([0., 0., 0.], dtype=float32)