如何将使用 Math.round 和整数值 FP 双精度的余数的代码调整为使用 SIMD 指令的 Java 代码?

问题描述 投票:0回答:1

我正在尝试修改此java代码以与SIMD指令兼容。

    int[] arr1 = {50002, 51000, 52040, 53078, 54065, 55004, 56077, 57073, 58020, 59000, 60095, 61046, 62051, 63018, 64480, 65460};
    int[] arr2 = {50, 57, 60, 63, 66, 70, 73, 74, 80, 81, 87, 88, 90, 92, 96, 103};
    int[] result = new int[16];
    for (int i = 0; i < 16; i++) {
        double a = arr1[i] / (double) arr2[i];
        int b = (int) ((Math.round(a * a) - 1) % 25) + 1;    // I need help to adapt this line of code.
        result[i] = b;
    }

我正在尝试编写适合SIMD指令的新java代码:

    int[] arr1 = {50002, 51000, 52040, 53078, 54065, 55004, 56077, 57073, 58020, 59000, 60095, 61046, 62051, 63018, 64480, 65460};
    int[] arr2 = {50, 57, 60, 63, 66, 70, 73, 74, 80, 81, 87, 88, 90, 92, 96, 103};
    int[] result = new int[16];
    var species = IntVector.SPECIES_PREFERRED;
    var Vec1 = IntVector.fromArray(species, arr1, 0);
    var Vec2 = IntVector.fromArray(species, arr2, 0);
    var RESULT = Vec1.mul(Vec1).div(Vec2.mul(Vec2);    // I need help to write the lines highlighted in the previous code.
    RESULT.intoArray(result, 0);

我根本找不到调整公式的方法。

编辑1: 由于我的知识有限(初学者),我现在注意到它比我想象的要复杂。 那么,让我更好地解释一下该函数的作用: 事实上,arr1 有 5000 万个素数(从 2 到 982451653),arr2 有 5000 个素数(从 1 到 5000)。 有 2 个循环,第一个循环 (arr2) 和第二个循环 (arr1)。 真正的java代码是:

    int[] arr1 = {2, 3, 5, 7, ... , 982451609,  982451629,  982451653}; // 50 million prime numbers.
    int[] arr2 = {1, 2, 3, 4, 5, ... , 4998, 4999, 5000};
    for (int i = 0; i < 5000; i++) {
        int[] result = new int[50000000];
        for (int j = 0; j < 50000000; j++) {
        double a = arr1[j] / (double) arr2[i];
            int b = (int) ((Math.round(a * a) - 1) % 25) + 1;    // I need help to adapt this line of code.
            result[j] = b;
        }
        // do something with result[] before discarding it
    }

例如: arr1[1034158] 是 16050707,arr2[452] 是 453

sqr(arr1/arr2) 等于 1255428344.7599

公式的结果应该是20(四舍五入1255428344.7599 -> 1255428345。那么,1255428345减去1255428325就是20。

java math simd
1个回答
0
投票

鉴于 SIMD 运算不直接支持模数运算,调整此代码以使用 SIMD 指令是相当困难的。此外,处理如此巨大的数组会导致性能和内存问题。以下是一次迭代的改编。

'导入jdk.incubator.vector.*;

int[] arr1 = {16050707};
int[] arr2 = {453};
int[] result = new int[arr1.length];

VectorSpecies<integer> species = IntVector.SPECIES_PREFERRED;
IntVector vec1 = IntVector.fromArray(species, arr1, 0);
IntVector vec2 = IntVector.fromArray(species, arr2, 0);

IntVector vector_result = vec1.mul(vec1).div(vec2.mul(vec2));

vector_result.intoArray(result, 0);

for(int i=0; i<result.length; i++){
 System.out.println(result[i]);
 }

`

© www.soinside.com 2019 - 2024. All rights reserved.