python 的 float.__eq__ 是如何用语言实现的?
How is python's float.__eq__ implemented in the language?
我知道比较两个浮点数是否相等的最佳方法通常是使用 math.isclose(float_a, float_b)
。但我很想知道 python 如果你只是 float_a == float_b
.
是怎么做到的
我想它是用 C 实现的,但它背后的逻辑是什么?
这是source code for float object comparisons
本质上。它看起来超级复杂,但这种复杂性主要在于处理 float
与 int
进行比较的情况(Python 中的 int
对象是任意大小的,它们不是t C-int 包装在 Python 对象中)。
但对于 float
和 float
的简单情况:
static PyObject*
float_richcompare(PyObject *v, PyObject *w, int op)
{
double i, j;
int r = 0;
assert(PyFloat_Check(v));
i = PyFloat_AS_DOUBLE(v);
/* Switch on the type of w. Set i and j to doubles to be compared,
* and op to the richcomp to use.
*/
if (PyFloat_Check(w))
j = PyFloat_AS_DOUBLE(w);
所以它只是从 float
对象创建两个 C double
s,然后(跳过所有 int 处理内容):
Compare:
switch (op) {
case Py_EQ:
r = i == j;
break;
case Py_NE:
r = i != j;
break;
case Py_LE:
r = i <= j;
break;
case Py_GE:
r = i >= j;
break;
case Py_LT:
r = i < j;
break;
case Py_GT:
r = i > j;
break;
}
return PyBool_FromLong(r);
它最终只是进行 C 级 ==
比较。所以它在幕后 而不是 math.isclose(float_a, float_b).
。
我知道比较两个浮点数是否相等的最佳方法通常是使用 math.isclose(float_a, float_b)
。但我很想知道 python 如果你只是 float_a == float_b
.
我想它是用 C 实现的,但它背后的逻辑是什么?
这是source code for float object comparisons
本质上。它看起来超级复杂,但这种复杂性主要在于处理 float
与 int
进行比较的情况(Python 中的 int
对象是任意大小的,它们不是t C-int 包装在 Python 对象中)。
但对于 float
和 float
的简单情况:
static PyObject*
float_richcompare(PyObject *v, PyObject *w, int op)
{
double i, j;
int r = 0;
assert(PyFloat_Check(v));
i = PyFloat_AS_DOUBLE(v);
/* Switch on the type of w. Set i and j to doubles to be compared,
* and op to the richcomp to use.
*/
if (PyFloat_Check(w))
j = PyFloat_AS_DOUBLE(w);
所以它只是从 float
对象创建两个 C double
s,然后(跳过所有 int 处理内容):
Compare:
switch (op) {
case Py_EQ:
r = i == j;
break;
case Py_NE:
r = i != j;
break;
case Py_LE:
r = i <= j;
break;
case Py_GE:
r = i >= j;
break;
case Py_LT:
r = i < j;
break;
case Py_GT:
r = i > j;
break;
}
return PyBool_FromLong(r);
它最终只是进行 C 级 ==
比较。所以它在幕后 而不是 math.isclose(float_a, float_b).
。