gpt4 book ai didi

c++ - fmod 还是不 fmod?

转载 作者:可可西里 更新时间:2023-11-01 18:28:03 24 4
gpt4 key购买 nike

我研究了旧代码,看到了这样一个函数:

inline double mod(double x, double y)
{
return x-y*floor(x/y);
}

fmod 是完全等效的,还是我遗漏了什么?

最佳答案

不,上面的例程与fmod() 不同。特别是对于一个参数是否定的情况,情况有所不同。

您的例程执行一个 floor(),它向下舍入到下一个整数。使用 fmod() 舍入类似于 trunc(),即趋向于零。

以下是 Open Group 标准 ( here ) 的摘录:

These functions shall return the value x- i* y, for some integer i such that, if y is non-zero, the result has the same sign as x and magnitude less than the magnitude of y.

If the correct value would cause underflow, and is not representable, a range error may occur, and either 0.0 (if supported), or an implementation-defined value shall be returned.

If x or y is NaN, a NaN shall be returned

If y is zero, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is infinite, a domain error shall occur, and either a NaN (if supported), or an implementation-defined value shall be returned.

If x is ±0 and y is not zero, ±0 shall be returned.

If x is not infinite and y is±Inf, x shall be returned.

If the correct value would cause underflow, and is representable, a range error may occur and the correct value shall be returned.

这很难理解,但第一段中的“幅度”一词说明四舍五入是向零舍入。

以下是 GCC 库更有用的文档的摘录:

These functions compute the remainder from the division of numerator by denominator. Specifically, the return value is numerator - n * denominator, where n is the quotient of numerator divided by denominator, rounded towards zero to an integer. Thus, fmod (6.5, 2.3) returns 1.9, which is 6.5 minus 4.6.

关于c++ - fmod 还是不 fmod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33632157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com