开发者

Java double just won't negate! Why?

For some reason, I'm having trouble negating a double and then returning it when a certain condition is met (which is being met). It stays positive, despite any coaxing otherwise.

开发者_JAVA百科
 public static double angleDiffNoAbs(double from, double to, double maxValue) {  
  double diff = to - from;
  double absdiff = Math.abs(diff);

  if (absdiff > maxValue) {
   double newdiff;

   boolean clockwise = false;

   if (from < to) {
    newdiff = maxValue;
    clockwise = true;
    System.out.println("c");
   } else {
    System.out.println("ac");
    newdiff = maxValue * -1.0d;
   }

   System.out.println("from: " + from + ", to: " + to + ", diff: " + diff + ", absdiff: " + absdiff + ", newdiff(limited): " + newdiff + ", wound: " + (clockwise ? "clockwise" : "anti-clockwise"));

   return newdiff;
  }

  double result = ((180d + diff) % 360d) - 180d;
  if (result < -180d) result = 360d + result;

  return result;
 }

The result in my JUnit test is:

c
from: -10.0, to: 20.0, diff: 30.0, absdiff: 30.0, newdiff(limited): 10.0, wound: clockwise
ac
from: 20.0, to: -10.0, diff: -30.0, absdiff: 30.0, newdiff(limited): 10.0, wound: anti-clockwise

I've been looking at this for ages and can't figure out the problem. The JUnit test is below (if it helps):

public class AngleDiffTest {
 @Test
 public void testAngleDiff() {
  double diff = Math.abs(Player.angleDiffNoAbs(353, 12, 360f));
  Assert.assertFalse("diff > 200: " + diff, diff > 200);
 }

 @Test
 public void testAngleDiff2() {
  double diff2 = Math.abs(Player.angleDiffNoAbs(360, 0, 360f));
  Assert.assertFalse("diff2 > 200: " + diff2, diff2 > 200);
 }

 @Test
 public void testAngleDiff3() {
  double diff2 = Math.abs(Player.angleDiffNoAbs(-10d, 20d, 10d));
  Assert.assertEquals("diff2 != 10.0: " + diff2, 10d, diff2);
 }


 @Test
 public void testAngleDiff4() {
  double diff2 = Math.abs(Player.angleDiffNoAbs(20d, -10d, -10d));
  Assert.assertEquals("diff2 != -10.0: " + diff2, -10d, diff2);
 } 
}


from: 20.0, to: -10.0, diff: -30.0, absdiff: 30.0, newdiff(limited): 10.0, wound: anti-clockwise

This result appears to be from your fourth test case (testAngleDiff4), in which you're passing a negative value of -10d for maxValue. When you do newdiff = maxValue * -1.0d, the two negatives cancel out, leaving you with a positive answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜