Skip to content

Instantly share code, notes, and snippets.

@joriki
Created February 6, 2023 12:54
Show Gist options
  • Save joriki/c07a2184f2b23cb678c039e4bbf45b0b to your computer and use it in GitHub Desktop.
Save joriki/c07a2184f2b23cb678c039e4bbf45b0b to your computer and use it in GitHub Desktop.
Generate an orthogonal matrix and a corresponding vector that satisfy certain constraints; see https://math.stackexchange.com/questions/4631555.
import java.util.Arrays;
import java.util.Random;
public class Question4631555 {
final static int l = 4;
final static int n = (l * (l - 1)) / 2;
final static Random random = new Random();
public static void main(String [] args) {
double [] [] u = new double [l] [l];
for (int i = 0;i < l;i++)
randomize (u [i]);
orthonormalize (u);
double [] [] m = new double [n] [n];
for (int i2 = 1,i = 0;i2 < l;i2++)
for (int i1 = 0;i1 < i2;i1++,i++)
for (int j2 = 1,j = 0;j2 < l;j2++)
for (int j1 = 0;j1 < j2;j1++,j++)
m [i] [j] = u [i1] [j1] * u [i2] [j2] - u [i1] [j2] * u [i2] [j1];
double [] [] p = new double [n] [n];
for (int i = 1;i < n - 1;i++)
for (int j = 0;j < n;j++)
p [i] [j] = m [0] [j] * m [i] [j];
Arrays.fill(p [0],1);
randomize (p [n - 1]);
orthonormalize (p);
for (int i = 0;i < n;i++)
p [n - 1] [i]++;
for (int i = 0;i < l;i++) {
for (int j = 0;j < l;j++)
System.out.print(u [i] [j] + " ");
System.out.println();
}
System.out.println();
for (int i = 0;i < n;i++)
System.out.println ("a_" + i + " : " + p [n - 1] [i]);
}
static void randomize (double [] x) {
for (int j = 0;j < x.length;j++)
x [j] = random.nextDouble();
}
static double dot (double [] x1,double [] x2) {
if (x1.length != x2.length)
throw new IllegalArgumentException();
double dot = 0;
for (int k = 0;k < x1.length;k++)
dot += x1 [k] * x2 [k];
return dot;
}
static void orthonormalize (double [] [] x) {
for (int i = 0;i < x.length;i++) {
orthogonalize (x,i);
normalize (x [i]);
}
}
static void orthogonalize (double [] [] x,int i) {
for (int j = 0;j < i;j++)
orthogonalize (x [i],x [j]);
}
static void orthogonalize (double [] x1,double [] x2) {
double dot = dot (x1,x2);
for (int k = 0;k < x1.length;k++)
x1 [k] -= dot * x2 [k];
}
static void normalize (double [] x) {
double sum = 0;
for (int j = 0;j < x.length;j++)
sum += x [j] * x [j];
sum = 1 / Math.sqrt(sum);
for (int j = 0;j < x.length;j++)
x [j] *= sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment