gpt4 book ai didi

c - 为什么我在数组的后半部分得到这个结果?

转载 作者:行者123 更新时间:2023-11-30 20:26:20 26 4
gpt4 key购买 nike

谁能告诉我为什么输出( Anew )是:

Anew = 0.000000    
Anew = 2.000000
Anew = 4.000000
Anew = 6.000000
Anew = 16.000000
Anew = 20.000000
Anew = 24.000000
Anew = 28.000000

而不是:

Anew = 0.000000    
Anew = 2.000000
Anew = 4.000000
Anew = 6.000000
Anew = 8.000000
Anew = 10.000000
Anew = 12.000000
Anew = 14.000000

代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mkl.h>

int main(int argc, const char* argv[]) {
int rows = 2, cols = 2, Layers = 2;
int PerLayerElmts = rows * cols;

float* A = malloc(PerLayerElmts * Layers * sizeof(*A));

// create A matrix
int ImagIdx;
for (int n = 0; n < Layers; n++) {
ImagIdx = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
A[n * PerLayerElmts + ImagIdx] = n * PerLayerElmts + ImagIdx;
ImagIdx++;
}
}
}
// print A matrix
for (int n = 0; n < Layers; n++) {
ImagIdx = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("\nA = %f", A[n * PerLayerElmts + ImagIdx]);
ImagIdx++;
}
}
}
float scalar = 2.0;
size_t AddressOffset = 0;
for (int i = 0; i < Layers; i++, AddressOffset += PerLayerElmts) {
// multiply A by scalar
cblas_sscal(PerLayerElmts * Layers, scalar, A + AddressOffset, 1);
}
// print A matrix
for (int n = 0; n < Layers; n++) {
ImagIdx = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("\n\nAnew = %f", A[n * PerLayerElmts + ImagIdx]);
ImagIdx++;
}
}
}

printf("\n");

free(A);

return 0;
}

我只是创建一个矩阵,然后使用 cblas 调用将每个元素乘以标量 ( 2 )。

我正在这样做,使用addressoffset作为层数。

问题出在第二层,其中元素乘以 4 而不是 2!

最佳答案

您调用cblas_sscal的方式似乎不正确。而不是

cblas_sscal( PerLayerElmts * Layers , scalar , A + AddressOffset , 1 );

我期望类似的东西

cblas_sscal( PerLayerElmts , scalar , A + AddressOffset , 1 );

因为您为每一层调用一次。

关于c - 为什么我在数组的后半部分得到这个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26180248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com