Inconsistency with Math.Round()

后端 未结 3 806
孤独总比滥情好
孤独总比滥情好 2021-01-20 17:11

I have two functions that are intended to contain angles between (-180,180] and (-π,π]. The intent is that given any angle from -inf to +inf it will retain the equivalent an

3条回答
  •  后悔当初
    2021-01-20 17:35

    Isn't this a case for a modulo operation?

    private double Wrap180(double value)
    {
        // exact rounding of corner values
        if (value == 180) return 180.0;
        if (value == -180) return 180.0;
    
        // "shift" by 180 and use module, then shift back.
        double wrapped = ((Math.Abs(value) + 180.0) % 360.0) - 180.0;
    
        // handle negative values correctly
        if (value < 0) return -wrapped;
        return wrapped;
    }
    

    It passes this tests

        Assert.AreEqual(170.0, wrap(-190.0));
        Assert.AreEqual(180.0, wrap(-180.0));
        Assert.AreEqual(-170.0, wrap(-170.0));
        Assert.AreEqual(0.0, wrap(0.0));
        Assert.AreEqual(10.0, wrap(10.0));
        Assert.AreEqual(170.0, wrap(170.0));
        Assert.AreEqual(180.0, wrap(180.0));
        Assert.AreEqual(-170.0, wrap(190.0));
    

提交回复
热议问题