为什么模数除法 (%) 仅适用于整数?

Why does modulus division (%) only work with integers?(为什么模数除法 (%) 仅适用于整数?)
本文介绍了为什么模数除法 (%) 仅适用于整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我最近遇到了一个问题 可以使用模数除法轻松解决,但输入是浮点数:

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.)

这篇关于为什么模数除法 (%) 仅适用于整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both(将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围为 0-255)
How to convert an enum type variable to a string?(如何将枚举类型变量转换为字符串?)
When to use inline function and when not to use it?(什么时候使用内联函数,什么时候不使用?)
Examples of good gotos in C or C++(C 或 C++ 中好的 goto 示例)
Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);(ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);)
Is TCHAR still relevant?(TCHAR 仍然相关吗?)