問題描述
我最近遇到了一個問題 可以使用模數除法輕松解決,但輸入是浮點數:
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.)
這篇關于為什么模數除法 (%) 僅適用于整數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!