cmod中的fmod()与matlab mod()相比如何?

时间:2017-02-09 08:36:41

标签: c matlab fmod mod

在matlab代码中

    Longitude =  mod(-1789.8916,360);

返回值10.108325

但是在C代码中

    Longitude = fmod(-1789.8916,360);

返回值-349.8916

我想要与c代码相同的值

2 个答案:

答案 0 :(得分:2)

matlab mod函数始终返回正值,但如果第一个参数为负,则C fmod函数(至少来自C11)将返回负值。 (在之前的C标准中,负面论证的准确行为取决于实施)。

因此,如果第一个参数为负且结果大于零,则可以通过从答案中减去360(在本例中)来转换matlab版本。

答案 1 :(得分:0)

mod函数总是在MATLAB中返回一个正值,从C11 fmod返回一个负值,如果第一个参数是负数。

您可以使用此函数来模拟MATLAB中fmod的行为

function m = fmod(a, b)

    % Where the mod function returns a value in region [0, b), this
    % function returns a value in the region [-b, b), with a negative
    % value only when a is negative.

    if a == 0
        m = 0;
    else
        m = mod(a, b) + (b*(sign(a) - 1)/2);
    end

end

说明:

sign(a)为正数时,

1a-1为正数时为a

(sign(a) - 1)/2因此分别为0-1

如果b为负数,则会从结果中减去a,从而得出所需的结果范围[-b, b)