Python numpy / math isclose-需要检查小于浮点数还是大于带阈值的浮点值

时间:2019-03-30 06:27:17

标签: python numpy

我在相似的行上读了多篇文章,我们试图根据相对公差比较两个浮点数(是的,这是浮点误差),并遇到了math.isClose()numpy.isclose() api。这些api效果很好,但是我的要求是确定两个浮点数的减法是否在阈值之内。因此,如果我发现小于或大于等于,那对我有用。

有什么主意我可以解决这个问题吗?

import numpy
import pandas as pd
from decimal import Decimal
data = {'first': [1.71, 1.72, 1.73, 1.74, 1.75, 1.76, 1.77, 1.78, 1.79, 1.80], 'second': [1.72, 1.73, 1.74, 1.75, 1.76, 1.77, 1.78, 1.79, 1.80, 1.81]}
df = pd.DataFrame(data, columns = ['first', 'second'])
df['isGtEq'] = df.apply (lambda row: (row['first'] - row['second']) >= 0.01, axis=1)
df['isclose'] = df.apply (lambda row: numpy.isclose(row['first'], row['second'], atol=0.01), axis=1)
df['absdiff'] = df.apply (lambda row: abs(row['first'] - row['second']), axis=1)
df['dec_diff'] = df.apply (lambda row: Decimal(row['first'] - row['second']), axis=1)

上述执行的结果是:

   first  second  isGtEq  isclose  absdiff  \
0   1.71    1.72   False     True     0.01
1   1.72    1.73   False     True     0.01
2   1.73    1.74   False     True     0.01
3   1.74    1.75   False     True     0.01
4   1.75    1.76   False     True     0.01
5   1.76    1.77   False     True     0.01
6   1.77    1.78   False     True     0.01
7   1.78    1.79   False     True     0.01
8   1.79    1.80   False     True     0.01
9   1.80    1.81   False     True     0.01

                                            dec_diff
0  -0.0100000000000000088817841970012523233890533...
1  -0.0100000000000000088817841970012523233890533...
2  -0.0100000000000000088817841970012523233890533...
3  -0.0100000000000000088817841970012523233890533...
4  -0.0100000000000000088817841970012523233890533...
5  -0.0100000000000000088817841970012523233890533...
6  -0.0100000000000000088817841970012523233890533...
7  -0.0100000000000000088817841970012523233890533...
8  -0.0100000000000000088817841970012523233890533...
9  -0.0100000000000000088817841970012523233890533...

0 个答案:

没有答案