import numpy as np
a = 2
b = 2.1
print(np.isclose(a, b))
実行結果
False
値にはnumpyのリストを指定することもできます。
その場合はそれぞれ同じインデックスの要素同士が近い値かどうか判定されます。
import numpy as np
a = np.array([1, 2, 3])
b = np.array([3, 2, 1])
print(np.isclose(a, b))
実行結果
[False True False]
ちなみにmathモジュールのiscloseではnumpyのリストは使うことはできません。
import math
a = np.array([1, 2, 3])
b = np.array([3, 2, 1])
print(math.isclose(a, b))
実行結果
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 6
3 a = np.array([1, 2, 3])
4 b = np.array([3, 2, 1])
----> 6 print(math.isclose(a, b))
TypeError: only length-1 arrays can be converted to Python scalars
もう一つおまけにmathモジュールのiscloseでは普通のリストもだめです。
import math
a = [1, 2, 3]
b = [3, 2, 1]
print(math.isclose(a, b))
実行結果
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[3], line 6
3 a = [1, 2, 3]
4 b = [3, 2, 1]
----> 6 print(math.isclose(a, b))
TypeError: must be real number, not list
コメント