-1

We're to find the difference between consecutive input values and return the largest change. My main issue is finding the correct operator to use (I think). Also I wanted it to work with negative values..

if(count > 0){
      change = Math.abs(temp) - Math.abs(temp2);
      UI.println(change);
      if(Math.abs(change) > Math.abs(bigChange)){
           bigChange = Math.abs(change);
      }
}
Javier
  • 12,100
  • 5
  • 46
  • 57

3 Answers3

1

Your use of abs is incorrect. Consider the case where temp is -1 and temp2 is 1. The difference between these values is 2, but your routine will compute it as 0.

Try:

if(count > 0) {
  change = Math.abs(temp - temp2);
  UI.println(change);
  if( change > bigChange ) {
    bigChange = change;
  }
}
ryanm
  • 2,979
  • 18
  • 22
0

if you want to find the change between to numbers you should use

change = Math.abs(temp- temp2);

instead of

 change = Math.abs(temp) - Math.abs(temp2);

Also you should initialize the variable

bigChange=0 

Furthermore, since variables change and bigChange are always greater than zero you can avoid calling again Math.abs method.

if(change > bigChange)
      {
          bigChange = change;
      }

is also correct.

Dimhatzo
  • 1
  • 1
0

It should be fairly simple:

int diff = temp - temp2;
max = Math.max(maxDifference, Math.abs(diff));
println(max).

Do you have any other requirement? Math.max and Math.min are quite optimized and are as fast as doing the comparison yourself. And it's a one-liner. See this answer as well for Math.max vs (a > b ? a : b)

Is Math.max(a,b) or (a>b)?a:b faster in Java?

Community
  • 1
  • 1
le-doude
  • 3,345
  • 2
  • 25
  • 55