Notes|numpy sample|Comparing whether two arrays are the same (regarding all nan as the same)

Part of the content in this article refers to the content generated by ChatGPT.

You can use the numpy function np.allclose()to compare whether two arrays are equal (approximately equal), this function supports:

  1. Set the relative error and absolute error, and regard the values ​​within the error range as equal;
  2. Two arrays are considered equal if their sums are both NaN.

The parameters of this function:

  • a, b: two arrays to be compared
  • rtol: Threshold of relative error, where relative error = ∣ actual value − reference value ∣ reference value relative error = \frac{|actual value - reference value|}{reference value}Relative error=Reference∣actual value reference value∣;If either relative or absolute error exceeds the threshold, it is considered unequal (optional, default 1e-5)
  • atol: Threshold of absolute error, where absolute error = ∣ actual value − reference value ∣ absolute error = |actual value - reference value|absolute error=∣actual valueReference value ; If either relative error or absolute error exceeds the threshold, it is considered unequal (optional, default1e-8)
  • equal_nan: whether to treat two arrays that are NaNboth equal (optional, default False)

The return value of this function: returns a Boolean value indicating whether the two arrays are equal within the specified precision range; if they are equal, it returns True, otherwise it returns False.

Example:

import numpy as np

a = np.array([1, 2, np.nan])
b = np.array([1, 2.00000001, np.nan])

# 判断a和b是否相等,将均为nan的视作相同
print(np.allclose(a, b, equal_nan=True))

The operation result is True, indicating that a and b are equal.

Guess you like

Origin blog.csdn.net/Changxing_J/article/details/130484875