Untitled
unknown
plain_text
3 years ago
4.2 kB
3
Indexable
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Main { static ExecutorService executor = Executors.newFixedThreadPool(10); static List<double[][]> generateMatrix(int nuknowns) { var random = new Random(); var coefs = new double[nuknowns][nuknowns]; var xs = new double[nuknowns]; for (int i = 0; i < nuknowns; i++) xs[i] = random.nextDouble(-10, 10); var b = new double[1][nuknowns]; for (int i = 0; i < nuknowns; i++) { double curB = 0.; for (int j = 0; j < nuknowns; j++) { var c = random.nextDouble(-10, 10); coefs[i][j] = c; curB += xs[j] * c; } b[0][i] = curB; } return List.of(coefs, b); } static void elimRow(double[] A, double[] K, double[] B, int i, int k) { double factor = A[k] / K[k]; B[i] -= factor * B[k]; for (int j = k; j < A.length; j++) A[j] -= factor * K[j]; } public static void solveInParallel(double[][] A, double[] B) throws ExecutionException, InterruptedException { int N = B.length; for (int k = 0; k < N; k++) { /** find pivot row **/ int max = k; for (int i = k + 1; i < N; i++) if (Math.abs(A[i][k]) > Math.abs(A[max][k])) max = i; /** swap row in A matrix **/ double[] temp = A[k]; A[k] = A[max]; A[max] = temp; /** swap corresponding values in constants matrix **/ double t = B[k]; B[k] = B[max]; B[max] = t; /** pivot within A and B **/ Future[] futures = new Future[N-k-1]; for (int i = k + 1; i < N; i++) { int finalI1 = i; int finalK1 = k; futures[i-k-1] = executor.submit(() -> elimRow(A[finalI1], A[finalK1], B, finalI1, finalK1)); } for (Future f : futures) f.get(); } /** back substitution **/ double[] solution = new double[N]; for (int i = N - 1; i >= 0; i--) { double sum = 0.0; for (int j = i + 1; j < N; j++) sum += A[i][j] * solution[j]; solution[i] = (B[i] - sum) / A[i][i]; } } //do the same thing but with parallel matricies //what can you do here public static void main(String[] args) throws ExecutionException, InterruptedException { for (int i = 1000; i <= 3000; i += 50) { List<double[][]> doubles = generateMatrix(i); long s1 = System.currentTimeMillis(); solveInParallel(doubles.get(0), doubles.get(1)[0]); long t2 = System.currentTimeMillis() - s1; System.out.println(t2); } executor.shutdown(); } } 228 205 216 231 266 290 326 360 419 433 509 549 657 764 791 871 1005 1054 1163 1252 1402 1578 1693 1828 2057 2265 2325 2474 2692 2930 3203 3303 3561 3820 4089 4292 4742 5122 5576 5694 5977 265 264 286 302 335 362 403 439 469 498 554 598 602 654 713 769 829 880 923 993 1068 1106 1184 1276 1370 1410 1548 1648 1755 1905 1953 2059 2185 2325 2476 2646 2801 2920 3142 3265 3470
Editor is loading...