Last active
October 17, 2017 08:30
Star
You must be signed in to star a gist
Dynamic scale exponential averager optimized for large vectors
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
package somepackage; | |
import java.util.Random; | |
public class ExponentialAverager { | |
public static void main(String[] args) { | |
int N_ITER = 50; | |
int N_VEC = 5; | |
double alpha = 0.1; | |
double k = 1 / (1 - alpha); | |
Random rand = new Random(42); | |
int[] indexes = new int[N_ITER]; | |
double[] xs = new double[N_ITER]; | |
for (int i = 0; i < N_ITER; i++) { | |
indexes[i] = rand.nextInt(N_VEC); | |
xs[i] = rand.nextDouble() * 3; | |
} | |
double s1[] = new double[N_VEC]; | |
double s2[] = new double[N_VEC]; | |
double scale = 1; | |
double scale_max = 100; | |
for (int i = 0; i < N_ITER; i++) { | |
scale = scale * k; | |
boolean rescale = false; | |
if (scale > scale_max) { | |
rescale = true; | |
for (int j = 0; j < N_VEC; j++) { | |
s2[j] /= scale; | |
} | |
scale = 1; | |
} | |
int index = indexes[i]; | |
double x = xs[i]; | |
for (int j = 0; j < N_VEC; j++) { | |
s1[j] *= (1 - alpha); | |
} | |
s1[index] += x * alpha; | |
s2[index] += x * alpha * scale; | |
for (int j = 0; j < N_VEC; j++) { | |
System.out.print(String.format("%c %7.6f/%7.6f %c ", | |
j == index ? '>' : ' ', s1[j], s2[j] / scale, | |
Math.abs(s1[j] - s2[j] / scale) / s1[j] > 1e-12 ? '!' | |
: ' ')); | |
} | |
System.out.println(String.format(" scale: %10.6f %s", scale, | |
rescale ? "(rescaled)" : "")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment