为什么模数师(%)仅整数的工作? [英] Why does modulus division (%) only work with integers?

查看:215
本文介绍了为什么模数师(%)仅整数的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近碰到<一个href=\"http://stackoverflow.com/questions/6091837/sin-and-cos-are-slow-is-there-an-alternatve/6091846#6091846\">an问题能够轻松使用模数师来解决,但投入是一个float:


  

给定一个周期函数(如),并且只能在时间范围内计算它(如[-π,π])的计算机功能,使功能可以处理任何输入。


在明显的解决办法是这样的:

 的#include&LT;&CMATH GT;浮罪(浮X){
    返回limited_sin((X + M_PI)%,(2 * M_PI) - M_PI);
}

为什么不工作的呢?我得到这个错误:

 

错误:类型双,双二进制运算符%无效操作数

有趣的是,它在Python的工作:

 

高清SIN(X):
    返回limited_sin((X + math.pi)%,(2 * math.pi) - math.pi)


解决方案

由于剩女正常的数学概念只适用于整数除法。即所需产生整数商师。

为了延长剩女实数,你必须引入一个新的混合型的操作,将产生概念的整数的商数为的真正的操作数。核心C语言不支持这样的操作,但它是作为一个标准库 FMOD 功能,以及 剩余 在C99的功能。 (注意,这些函数是不一样的,并且有一定的特殊性,特别是,它们不遵循整数除法的舍入的规则。)

I recently ran into an issue that could easily be solved using modulus division, but the input was a float:

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 %

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.

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

这篇关于为什么模数师(%)仅整数的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆