package org.nusco.narjillos.shared.physics;

/**
 * Fast pre-calculated tables for sin and cos.
 * 
 * On my Mac, they take about 1 extra second at startup (and some memory, of
 * course). After that, they're about 4 times faster than Math.sin() and
 * Math.cos().
 */
public class FastMath {

	private final static double STEP = 0.0001;

	private static double[] sin = new double[(int) (360 / STEP)];
	private static double[] cos = new double[(int) (360 / STEP)];

	static {
		initialize();
	}

	private static void initialize() {
		synchronized (sin) {
			for (int i = 0; i < sin.length; i++) {
				double angleRadians = Math.toRadians(i * STEP);
				sin[i] = Math.sin(angleRadians);
				cos[i] = Math.cos(angleRadians);
			}
		}
	}

	public synchronized static double sin(double angle) {
		int index = toIndex(angle);
		synchronized (sin) {
			return sin[index];
		}
	}

	public static double cos(double angle) {
		int index = toIndex(angle);
		synchronized (sin) {
			return cos[index];
		}
	}

	private static double normalize(double angle) {
		double result = angle % 360;
		if (result < 0)
			result = 360 + result;
		if (result >= 360) // 360.0 can still happen because of roundings
			result = 0;
		return result;
	}

	private static int toIndex(double angle) {
		return (int) (normalize(angle) / STEP);
	}
}

@@ -529,32 +529,8 @@
 ) %7B%0A
-%09%09synchronized (sin) %7B%0A%09
 %09%09fo
@@ -566,17 +566,16 @@
  i++) %7B%0A
-%09
 %09%09%09doubl
@@ -620,17 +620,16 @@
 EP);%0A%09%09%09
-%09
 sin%5Bi%5D =
@@ -653,17 +653,16 @@
 dians);%0A
-%09
 %09%09%09cos%5Bi
@@ -693,17 +693,12 @@
 s);%0A
-%09
 %09%09%7D%0A
-%09%09%7D%0A
 %09%7D%0A%0A
@@ -705,29 +705,16 @@
 %09public 
-synchronized 
 static d
@@ -737,36 +737,35 @@
  angle) %7B%0A%09%09
-int index = 
+return sin%5B
 toIndex(angl
@@ -770,58 +770,10 @@
 gle)
+%5D
 ;
-%0A%09%09synchronized (sin) %7B%0A%09%09%09return sin%5Bindex%5D;%0A%09%09%7D
 %0A%09%7D%0A
@@ -821,20 +821,19 @@
 %7B%0A%09%09
-int index = 
+return cos%5B
 toIn
@@ -846,58 +846,10 @@
 gle)
+%5D
 ;
-%0A%09%09synchronized (sin) %7B%0A%09%09%09return cos%5Bindex%5D;%0A%09%09%7D
 %0A%09%7D%0A

Remove synchronization from trigonometric tables to make them faster