C++ 余数和 NumPy/Python 余数之间的区别

Tom*_*ean 2 c++ python numpy

在C++中,代码如下:

#include <math.h>
#include <iostream>

int main() {
    std::cout << remainder(-177.14024960054252, 360) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

使用 x86-64 GCC 12.2 编译(https://godbolt.org/z/43MzbE1ve

输出:

-177.14
Run Code Online (Sandbox Code Playgroud)

然而在Python中:

-177.14
Run Code Online (Sandbox Code Playgroud)

两者输出:

182.85975039945748
Run Code Online (Sandbox Code Playgroud)

根据 numpy 文档,np.remainder正在执行 IEEE 余数函数。根据 C++ 文档,remainder还执行 IEEE 余数函数。

为什么这两个数字不同?

jus*_*bie 5

因为np.remainder没有使用 IEEE 余数函数。

\n

引用文档

\n
\n

计算函数的余数floor_divide。它相当于 Python 模运算符x1 % x2,并具有与除数相同的符号x2。与\n 等效的 MATLAB 函数np.remainder是 mod。

\n
\n

它还有一个警告,指出它与 Python 3.7\xe2\x80\x99s 和 C\xe2\x80\x99s 余数不同math.remainder

\n
\n

这不应与以下内容混淆:

\n

Python 3.7\xe2\x80\x99smath.remainder和 C\xe2\x80\x99s 余数,用于计算 IEEE\n余数,它们是round(x1 / x2).

\n

MATLAB rem 函数和/或 C % 运算符\n其补集int(x1 / x2).

\n
\n

有关 Python%和 C之间的区别%,请参见此处

\n