User:Rednaxela/FastTrig
Jump to navigation
Jump to search
A little class for fast trig lookups. Tests show that:
- When used with the sin/cos static methods, it ranges from twice as slow, to three times as fast, depending on how much of a chance the JIT has to optimize
- When you inline the index-calculation code into your own code (see usage in the main method) instead of using static methods, it ranges from just slightly faster, up to three times as fast.
- Increasing the number of divisions has no impact on runtime performance, only initialization time and memory consumption.
This could provide some measurable speedup to intensive play-it-forward guns or precise prediction in surfers. Cheers!
package ags.util;
public class FastTrig {
public static final int DIVISIONS = 2880;
public static final double[] sineTable = new double[DIVISIONS];
public static final double[] cosineTable = new double[DIVISIONS];
public static final void init() {
for (int i=0; i<DIVISIONS; i++) {
double value = i*Math.PI*2/DIVISIONS;
sineTable[i] = Math.sin(value);
cosineTable[i] = Math.cos(value);
}
}
public static final double sin(double value) {
return sineTable[(int)(value/(Math.PI*2/DIVISIONS) + 0.5) % DIVISIONS];
}
public static final double cos(double value) {
return cosineTable[(int)(value/(Math.PI*2/DIVISIONS) + 0.5) % DIVISIONS];
}
/*
public static void main(String[] args) {
init();
double v=12.23;
long ms;
ms = -System.nanoTime();
for (int i=0; i<100000; i++)
v += Math.sin(i*Math.PI*2/1000);
ms += System.nanoTime();
System.out.println(String.format("Done in %4.4f seconds", ms/1E9));
ms = -System.nanoTime();
for (int i=0; i<100000; i++) {
double value = i*Math.PI/1000;
v += sineTable[(int)(value/(Math.PI*2/DIVISIONS) + 0.5) % DIVISIONS];
}
ms += System.nanoTime();
System.out.println(String.format("Done in %4.4f seconds", ms/1E9));
}
*/
}
--Rednaxela 09:18, 3 March 2009 (UTC)