Floating Point Modulo Operation

后端 未结 4 868
梦谈多话
梦谈多话 2020-12-18 18:28

I am trying to implement the range reduction operation for trigonometry. But instead I think it might be better to just perform a modulo pi/2 operation on incoming data. I

4条回答
  •  盖世英雄少女心
    2020-12-18 19:17

    The algorithm you want, to limit a floating point value between 0 and some modulus n:

    Double fmod(Double value, Double modulus)
    {
        return value - Trunc(value/modulus)*modulus;
    }
    

    for example pi mod e (3.14159265358979 mod 2.718281828459045)

    3.14159265358979 / 2.718281828459045 
       = 1.1557273497909217179
    
    Trunc(1.1557273497909217179)
       = 1
    
    1.1557273497909217179 - 1
       = 0.1557273497909217179
    
    0.1557273497909217179 * e
       = 0.1557273497909217179 * 2.718281828459045
       = 0.42331082513074800
    

    pi mod e = 0.42331082513074800

提交回复
热议问题