Re: Beginner Projects



Joshua Cranmer wrote:
Roedy Green wrote:
On Thu, 30 Aug 2007 00:32:11 -0400, Lew <lew@xxxxxxxxxxxxx> wrote,
quoted or indirectly quoted someone who said :

. OTOH, this counts as "premature optimization" in many cases.

It is simpler code, so I don't count it as optimisation. Optimisation
that gets you in trouble is verbose, harder-to-maintain code. I
figure every student should be familiar with odd/even idiom.

Sometimes it can save you.

int mid = (low + high) / 2;
int mid = (low + high) >>> 1;

The first one breaks when low + high > 2^31-1, the second one doesn't (only when low + high > 2^32 - 1).

Maybe there is something I'm not understanding here. I just did some
tests, and as far as I can tell, whenever they differ the first method
gets the right answer. Could you suggest some inputs that demonstrate
the benefit of the second version?

Results:

low=0, high=2147483647, mid1=1073741823, mid2=1073741823
! low=-5, high=-3, mid1=-4, mid2=2147483644
! low=-5, high=-2, mid1=-3, mid2=2147483644
low=-100, high=2147483647, mid1=1073741773, mid2=1073741773
! low=-2147483648, high=1000, mid1=-1073741324, mid2=1073742324
! low=-2147483648, high=2147483647, mid1=0, mid2=2147483647


Test program:

public class MidTest {
public void test(int low, int high){
int mid1 = (low + high) / 2;
int mid2 = (low + high) >>> 1;
if(mid1 != mid2){
System.out.print("! ");
}
System.out.printf(
"low=%d, high=%d, mid1=%d, mid2=%d%n",
low,high,mid1,mid2);
}
public static void main(String[] args) {
MidTest tester = new MidTest();
tester.test(0,Integer.MAX_VALUE);
tester.test(-5,-3);
tester.test(-5,-2);
tester.test(-100,Integer.MAX_VALUE);
tester.test(Integer.MIN_VALUE,1000);
tester.test(Integer.MIN_VALUE,Integer.MAX_VALUE);
}
}

.



Relevant Pages

  • Re: Plugin architectures
    ... I've never set a classpath in a ... manifest file, I really should do. ... If you make a short test program like this ... public static void main(String... ...
    (comp.lang.java.programmer)
  • Re: multithreading
    ... get an answer for your system is the write a small test program ... public static void main{ ... This will give you a rough answer. ... Mine broke after 7122 ...
    (comp.lang.java.gui)
  • JVM Memory leak after interrupting threads??
    ... Why is the JVM not reclaiming the ... See below for simple test program ... public static void main ...
    (comp.lang.java.programmer)