4 posts

# Fibonacci (1000000000) Challenge Blog

Posted by kabutz-JavaNet Feb 24, 2012

We all know the standard Fibonacci recursive algorithm:

public BigInteger f(int n) {
if (n == 0) return BigInteger.ZERO;
if (n == 1) return BigInteger.ONE;
return f(n - 1).add(f(n - 2));
}

Your challenge is to find the first 10 bytes and the last 10 bytes of f(1_000_000_000). That's right, fibonacci of one billion. Please post the answer here, in hexadecimal.

My solution took 2500 seconds on an 8-core machine, utilizing all the cores.

Winner will get a special mention in my next Java Specialists' Newsletter (http://www.javaspecialists.eu).

One last hint. Fork/Join is very useful to speed up your calculation.

# Java Mind Gymnastics Blog

Posted by kabutz-JavaNet Feb 16, 2012

I like a good Java puzzle.  The trickier the better.  In this article I will tell you about a new set of puzzles by Wouter Coekaerts that will melt your Java brain.

About five years ago, I was suckered into participating in a Java Black Belt competition at a Java Tech Days in London.  This was in the days before Her Royal Highness decided she had had enough South African visitors and thus closed the door for me by asking us to get visas.  Since I live on an island in the Mediterranean, acquiring a visa means flying to Athens and handing over my passport to the British Embassy for 6 weeks.  I travel at least once a month, so it will be a while before I can enjoy the warmth of English beer again.  The Java Black Belt competition consists of a bunch of questions, ranging from hard to very hard.  You have a limited time to answer them.  If you are lucky, you get given a set of relatively easy questions.  During the competition, I was lucky to get a high enough score, so that I got to the top of the scoreboard.  It was not a brilliant score by any means.  Olivier Croisier, my French instructor, scored a perfect 100% in the Sun Java Programmers Certification.  My score was probably about 95%.  Fortunately, someone recognized my name and told his buddies that they had no chance of dethroning me.  As a result, no one tried after me and I won a book called the Java Puzzlers.  I reviewed it on The Java Specialists' Newsletter.

Olivier Croisier publishes some excellent Java puzzles in his blog called "The Coder's Breakfast".  It is in French, but don't let that put you off.  Olivier does a very nice job of translating it to English for those of us who do not understand a word of French.  The name conjures up images of sitting in a Parisian cafe with a newspaper, watching the world go by whilst the butter is melting in the warm croissant and your cup of hot coffee is filling the room with a pleasant aroma.

And lastly, we have a hot new contender on the puzzle scene, Wouter Coekaerts.  He sent me some of his puzzles about a year ago and I've been begging him since then to please release them to the world.  They are funny and very challenging.  Definitely something for an advanced Java programmer.  You can use some dirty tricks, but nothing that would break the security manager.  Here is his first puzzle.  After a couple of weeks, Wouter will show the solution and his next puzzle.

# Pushing the Limits in Java's Random Blog

Posted by kabutz-JavaNet Feb 13, 2012

Welcome to the 198th issue of The Java(tm) Specialists' Newsletter sent to you from Chania in Greece. My readers in colder climates frequently get annoyed when I tell them that "life's a beach". They imagine us having constant sun here. It's not true. We do sometimes have torrential rains and cold weather. It even snows here occasionally. In fact, the delivery truck for my heating oil arrived as I was writing this.

### Pushing the Limits in Java's Random

My previous newsletter caused quite a stir. I saw lots of wrong answers and some excellent explanations. Quite a few thought that Math.random() did indeed sometimes return 1.0. It does not, but the value is sometimes close enough to 1.0 that we lose precision in the rounding.

Here is what the nextDouble() calculation looks like in java.util.Random:

public double nextDouble() {
return (((long)(next(26)) << 27) + next(27))
/ (double)(1L << 53);
}

One of our most thorough readers, Dr. Wolfgang Laun, went on a voyage of discovery to find out what the highest number was that could possibly be returned by Math.random(). This newsletter is a summary of his findings, plus some other tidbits that I discovered. Dr. Laun lives in Vienna in Austria and works for Thales as their local software guru. I've had the pleasure of meeting him personally and been invited for dinner at his house. He is probably the most intelligent human being I have met. And he also has a great sense of humour and a keen curiosity of how the world works. I am honoured to count him as a friend.

The first question that Wolfgang tried to answer is: Can (int)(Math.random() + 1) ever return 2? I thought it could. The calculation for producing the double is to make up a 53 bit number and to then divide it by 2^53. This means that the maximum possible number would be ((2^53)-1)/(2^53), or 0.9999999999999999. You can calculate this easily:

System.out.println((((1L << 53) - 1)) / (double) (1L << 53));

If we use the standard Random calculation as shown in makeDouble(), if we add 1 and cast it to an int, the result will be 2. For example:

public class CloseToOne {
public static double makeDouble(long first, long second) {
return ((first << 27) + second) / (double) (1L << 53);
}

public static void main(String[] args) {
long first = (1 << 26) - 1;
long second = (1 << 27) - 1;

System.out.println(makeDouble(first, second));
System.out.println((int)(makeDouble(first, second)+1));

second--;
System.out.println(makeDouble(first, second));
System.out.println((int)(makeDouble(first, second)+1));
}
}

In our previous newsletter, "meaning" was sometimes incremented by two, when Math.random was close enough to 1 and "meaning" was large enough. For example, if "meaning" is 100_000_000, we don't need to be as close to 1 as if "meaning" is 1.

public class CloseToOne2 {
public static void main(String[] args) {
double d = 0.999999993;
System.out.println("d = " + d);
int i = (int) (1 + d);
System.out.println("i = " + i);
int j = (int) (100_000_000 + d);
System.out.println("j = " + j);
}
}

The question is, can Math.random() return a significantly large number that is less than 1.0, but that makes(int)(Math.random() + 1) return 2? I thought so, but Wolfgang proved me wrong.

Java's random calculation is based on the 48-bit seed, linear congruential formula described in The Art of Computer Programming, Volume 2by Donald Knuth in Section 3.2.1. This is also described on Wikipedia.

The point to note is that it is based on a 48-bit seed. In order for (int)(Math.random() + 1) to be 2, all the bits would have to be set on the left. If it is just one less, then the double would equal 0.9999999999999998 and this would not round up to 2.

Since the next random value is based on the current value, all we would need to check is whether there exists a 48-bit number with the lower 26 bits set, such that the next number has the lower 27 bits set. If we find such a number, then we can conclude that at least in theory, it is possible for Math.random() to return0.9999999999999999. We would still need to establish for what random seed we could get this number. If we did not find such a number, then we could conclude that it was not possible.

Wolfgang wrote the code to calculate the largest number that could be returned by Math.random():

/**  * @author Wolfgang Laun  */

public class FindRandom {
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;

public static double makeDouble(long pre, long post) {
return ((pre << 27) + post) / (double) (1L << 53);
}

private static long setbits(int len, int off) {
long res = (1L << len) - 1;
return res << off;
}

/**     * A random double is composed from two successive random     * integers.     * The most significant 26 bits of the first one are taken and     * concatenated with the most significant 27 bits of the second     * one.     * (ms(ri1,26)) << 27 + (ms(ri2,27))     * This is divided by (double)(1L << 53) to obtain a     * result in [0.0, 1.0).     * To find the maximum random double, we assume that     * (ms(ri1,m26))     * is a maximum (all 1b) and vary the remaining 22 bits from     * 0 to m22, inclusive. Assuming this to be ri1, we perform the     * calculation according to Random.next() to obtain is     * successor, our ri2. The maximum of the most significant 27     * bits of all ri2 would then be the second part of the maximum     * 53-bit integer used for a double random's mantissa.    */
private static void findMaxDouble() {
long ones = setbits(26, 22);
System.out.println("ones: " + Long.toHexString(ones));
long maxpost = setbits(22, 0);
System.out.println("maxpost: " + Long.toHexString(maxpost));
long maxintw = 0;
for (long post = 0; post <= maxpost; post++) {
long oldseed = ones + post;
long intw = nextseed >>> (48 - 27);
if (intw > maxintw) {
maxintw = intw;
}
}
System.out.println("maxintw: " + Long.toHexString(maxintw));
long b26 = setbits(26, 0);
System.out.println("b26: " + Long.toHexString(b26));
double d = makeDouble(b26, maxintw);
System.out.println("max. double: " +
Double.toHexString(d) + " = " + d);
}

private static void findMinDouble() {
long b26 = 0L;
long zeroes = 0L;
long maxpost = setbits(22, 0);
long minintw = 0x7fffffffffffffffL;
for (int post = 0; post < maxpost; post++) {
long oldseed = zeroes + post;
long intw = nextseed >>> (48 - 27);
if (intw < minintw) {
minintw = intw;
}
}
System.out.println("minintw: " + minintw);
double d = makeDouble(b26, minintw);
System.out.println("min. double: " +
Double.toHexString(d) + " = " + d);
}

public static void main(String[] args) {
findMaxDouble();
double belowOne = Math.nextAfter(1.0, 0.0);
System.out.println("Biggest double below 1.0 is: " +
Double.toHexString(belowOne) + " = " + belowOne);
findMinDouble();
}
}

From this, we can calculate that the highest number that can be returned by Math.random() is 0.999999999999996, whereas the highest double less than 1.0 is 0.9999999999999999, a difference of .0000000000000039.

#### Concurrency

We could stop here, were it not for concurrency. However, the Math.random() method delegates to a shared mutable instance of Random. Since they use atomics, rather than locking, it is impossible for the compound nextDouble() method to be atomic. Thus it is possible that in between the two calls to next(27) and next(26), other threads call next(). Remember the code for Random.nextDouble() from earlier:

public double nextDouble() {
return (((long)(next(26)) << 27) + next(27))
/ (double)(1L << 53);
}

In theory, if you had thousands of threads calling Math.random() at the same time, your thread could be swapped out for long enough, so that (int)(Math.random() + 1) could return 2. The probability of this happening might be greater than zero, but it is infinitesimally small. For example, in my experiments I did find a value of next(26) for which, if it was swapped out long enough and other threads had called next(27) 105 times, next(27) would return a number with all bits set. As Wolfgang told me, I'm rapidly entering into the realms of the metaphysical here.

As of Java 7, we should never again use Math.random(). Java 7 gives us a new ThreadLocalRandom class that has one unshared Random instance per thread. Since it is an unshared object, they do not need to have any synchronization to prevent data races. As a result it is blazingly fast.

We can use it like this:ThreadLocalRandom.current().nextInt(3000);

In this example, we construct 20 buttons and let them change color at a random interval using ThreadLocalRandom. I will go over this code again in another newsletter, as it also demonstrates the new Java 7 Phaser class.

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.concurrent.*;

/**  * @author Heinz Kabutz  */
public class Blinker extends JFrame {
setLayout(new GridLayout(0, 4));
}

final Phaser phaser = new Phaser(buttons) {
protected boolean onAdvance(int phase, int parties) {
return phase >= blinks - 1 || parties == 0;
}
};
for (int i = 0; i < buttons; i++) {
final JComponent comp = new JButton("Button " + i);
comp.setOpaque(true);
final Color defaultColor = comp.getBackground();
changeColor(comp, defaultColor);
public void run() {
try {
do {
Color newColor = new Color(rand.nextInt());
changeColor(comp, newColor);
changeColor(comp, defaultColor);
Toolkit.getDefaultToolkit().beep();
} while (!phaser.isTerminated());
} catch (InterruptedException e) {
}
}
}.start();
}
}

private void changeColor(
final JComponent comp, final Color color) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
comp.setBackground(color);
invalidate();
repaint();
}
});
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
WindowConstants.EXIT_ON_CLOSE);
}
});
}
}

If you run the Blinker with a version of Java 7 older than 1.7.0_02, you will notice that all the colors and delays are always the same. This is due to a bug in the constructor of java.util.Random, which failed to set the seed correctly on the subclass. Time to upgrade to the latest version of Java 7. Note that if you are using Mac OS X Snow Leopard or Leopard, the Mac OS X Port installerwill tell you that you need to upgrade to Lion. Instead, I used Pacifistto extract the DMG file. I am not ready to install Lion on my work machines yet.

#### (int)(Math.random() * some_int)

A common code idiom is to multiply the result of Math.random() with some integer value. There are several reasons not to do that anymore. First off, Math.random() is using a shared mutable instance of Random, thus it needs to be synchronized. It does use atomics to eliminate locking, but with lots of threads calling Math.random(), you might still need to redo your work several times until you emerge as the winner.

The second reason is that Math.random() calls nextDouble(), which as we have seen, will call next(bits) twice.

The third reason is that nextDouble() * int is more biased. We will get a fairer distribution if we call nextInt(upto).

#### One Last Thing

Concurrency allows us to do some strange things. For example, we can set the seed on a shared mutable Random instance so that eventually, (int)(random.nextDouble() + 1) will return 2. Here is the code:

public class MathTeaser {
public static void main(String[] args) {
final Random random = new Random();
public void run() {
while(true) {
random.setSeed(51102269); // causes 2^26-1 as next(26)
random.setSeed(223209395); // causes 2^27-1 as next(27)
}
}
};
seeder.setDaemon(true);
seeder.start();

while(true) {
double num = random.nextDouble();
if ((int)(num + 1) == 2) {
System.out.println("Yes, random.nextDouble() can: " + num);
break;
}
}
}
}

Thanks to Dr. Wolfgang Laun for the fascinating discussions of how Random really works and for your contribution in this newsletter.

Kind regards

Heinz

# What is the meaning of life? Blog

Posted by kabutz-JavaNet Dec 21, 2011

A few weeks ago I updated my age to be a factor of 2 and 5.  It is the perfect age to reflect what life is all about.  Some men don a leather jacket and ride around on a Harley.  But as a geek I know exactly where to turn - my beloved computer.

I needed a long-running method for the new concurrency course I am writing.  Something that would take about 15 seconds and that would keep the CPU busy at 100%.  Also, since life throws us random events, we would have to include a call to Math.random() in the calculation.  In my next article I will explain why Math.random() is dead, long live Java 7, but for now we will call it in order to be super slow.

public class MeaningOfLife {
int meaning = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 20; j++) {
for (int k = 0; k < 300; k++) {
for (int m = 0; m < 7000; m++) {
meaning += Math.random() + 1;
}
}
}
}
return String.valueOf(meaning).replaceAll("0*\$", "");
}

public static void main(String[] args) {
}
}

Think about what the output should be before you run it. Then try it out, preferably with the -server switch. On my machine it takes 15 seconds to find the meaning of life with -server and 25 seconds with -client. Patience is apparently a virtue, though I would not be able to confirm or deny that.  Never had patience, which is why I always want the fastest meanest computer that I can get.

The question is: Why is it giving this result? And why does it even compile?

By date: