Created
July 23, 2021 20:43
-
-
Save shelajev/132dd797ad9f904e50c323a03f60e79c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SignalCorrelation { | |
/** Approximate {@code sin(i / 1000)}. */ | |
public static double sin(int i) { | |
double x = i / 1000.0; | |
double term3 = (x*x*x) / (3 * 2 * 1); | |
double term5 = (x*x*x*x*x) / (5 * 4 * 3 * 2 * 1); | |
return x - term3 + term5; | |
} | |
public static double[] sinTable(int n) { | |
double[] table = new double[n]; | |
for (int i = 0; i < n; i++) { | |
table[i] = sin(i); | |
} | |
return table; | |
} | |
/** Approximate {@code cos(i / 1000)}. */ | |
public static double cos(int i) { | |
double x = i / 1000.0; | |
double term2 = (x*x) / (2 * 1); | |
double term4 = (x*x*x*x) / (4 * 3 * 2 * 1); | |
return 1 - term2 + term4; | |
} | |
public static double[] cosTable(int n) { | |
double[] table = new double[n]; | |
for (int i = 0; i < n; i++) { | |
table[i] = cos(i); | |
} | |
return table; | |
} | |
public static double correlate(double[] a, double[] b) { | |
double correlation = 0.0; | |
for (int i = 0; i < a.length; i++) { | |
correlation += a[i] * b[i]; | |
} | |
return correlation; | |
} | |
public static double computeCorrelation(double[] a, double[] b) { | |
return correlate(a, b); | |
} | |
public static void main(String[] args) { | |
int n = args.length > 0 ? Integer.valueOf(args[0]) : 100_000_000; | |
for (int j = 0; j < 10; j++) { | |
long tablesStart = System.nanoTime(); | |
double[] sin = sinTable(n); | |
double[] cos = cosTable(n); | |
long tablesEnd = System.nanoTime(); | |
System.out.println("table computation: " + (tablesEnd - tablesStart) / 1_000_000 + " ms"); | |
long correlationStart = System.nanoTime(); | |
double sinSin = computeCorrelation(sin, sin); | |
double sinCos = computeCorrelation(sin, cos); | |
double cosSin = computeCorrelation(cos, sin); | |
double cosCos = computeCorrelation(cos, cos); | |
double sinSinNormalized = sinSin / sinSin; | |
double sinCosNormalized = sinCos / Math.sqrt(sinSin * cosCos); | |
double cosSinNormalized = cosSin / Math.sqrt(cosCos * sinSin); | |
double cosCosNormalized = cosCos / cosCos; | |
long correlationEnd = System.nanoTime(); | |
System.out.println("sin/sin correlation: " + sinSinNormalized); | |
System.out.println("sin/cos correlation: " + sinCosNormalized); | |
System.out.println("cos/sin correlation: " + cosSinNormalized); | |
System.out.println("cos/cos correlation: " + cosCosNormalized); | |
System.out.println("correlation: " + (correlationEnd - correlationStart) / 1_000_000 + " ms"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment