Xazker's blog

By Xazker, 14 years ago, In English

The following code with run keys "-ea -Xmx256m -Xss64m" gives on my computer (Core2Duo 1.83Ghz, L2 cache 2Mb, ram 2Gb)  this output:

1.751140997 sec
0.216811633 sec

Recursion works extremely slow. What's wrong with it?

public class DoYouWantToSeeSomeMagic {
static class List {
List next;

public List(List next) {
this.next = next;
}
}

private static List createListSlow(int n) {
if (n == 0) {
return new List(null);
} else {
return new List(createListSlow(n - 1));
}
}

private static List createListFast(int n) {
List[] list = new List[n + 1];
list[0] = new List(null);
for (int i = 1; i <= n; ++i) {
list[i] = new List(list[i - 1]);
}
return list[n];
}

public static void main(String[] args) {
final int N = 1 << 20;
{
long time = System.nanoTime();
createListSlow(N);
System.err.println((System.nanoTime() - time) / 1e9 + " sec");
}
{
long time = System.nanoTime();
createListFast(N);
System.err.println((System.nanoTime() - time) / 1e9 + " sec");
}
}
}

If I change N to (1 << 19) the output is:

0.129561439 sec
0.129751965 sec

Full text and comments »

  • Vote: I like it
  • +10
  • Vote: I do not like it

By Xazker, 15 years ago, translation, In English
I always thought that standard libraries work not so fast, but at least correctly. It was really surprise, to see such strange results from code given below.
java.awt.geom 
Class Line2D

ptLineDist

public static double ptLineDist(double X1,
                                double Y1,
                                double X2,
                                double Y2,
                                double PX,
                                double PY)

Returns the distance from a point to a line. The distance measured is the distance between the specified point and the closest point on the infinitely-extended line defined by the specified coordinates. If the specified point intersects the line, this method returns 0.0.

System.out.println(Line2D.ptLineDist(0, 0, 1, 200, 1, 199));
System.out.println(Line2D.ptLineDist(0, 0, 1, 2000, 1, 1999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 20000, 1, 19999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 200000, 1, 199999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 2000000, 1, 1999999));
System.out.println(Line2D.ptLineDist(0, 0, 1, 20000000, 1, 19999999));


0.004999937545118085
5.000601076713239E-4
0.0                                      --- the distance from point (1,19999) to line (0,0) (1, 20000) equals 0 !!!
0.0
0.0
0.25                                    --- no sense

Who can explain that?

Full text and comments »

  • Vote: I like it
  • +7
  • Vote: I do not like it