问题描述
我最近遇到了一个问题 可以使用模数除法轻松解决,但输入是浮点数:
I recently ran into an issue that could easily be solved using modulus division, but the input was a float:
给定一个周期函数(例如sin
)和一个只能在周期范围内计算它的计算机函数(例如[-π, π]),制作一个可以处理任何输入的函数.
Given a periodic function (e.g.
sin
) and a computer function that can only compute it within the period range (e.g. [-π, π]), make a function that can handle any input.
明显"的解决方案类似于:
The "obvious" solution is something like:
#include <cmath>
float sin(float x){
return limited_sin((x + M_PI) % (2 *M_PI) - M_PI);
}
为什么这不起作用?我收到此错误:
Why doesn't this work? I get this error:
error: invalid operands of types double and double to binary operator %
有趣的是,它确实适用于 Python:
Interestingly, it does work in Python:
def sin(x):
return limited_sin((x + math.pi) % (2 * math.pi) - math.pi)
推荐答案
因为余数"的正常数学概念仅适用于整数除法.即生成整数商所需的除法.
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
为了将余数"的概念扩展到实数,您必须引入一种新的混合"操作,该操作将为实数操作数生成整数商.核心 C 语言不支持这种操作,但它作为标准库提供 fmod
函数,以及 remainder
函数C99.(注意,这些函数并不相同,有一些特殊性.特别是,它们不遵循整数除法的舍入规则.)
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod
function, as well as remainder
function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
这篇关于为什么模数除法 (%) 仅适用于整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!