[英]How does C store a double into an allocated array of type float?
I am changing my program from floating-point precision to double precision. 我正在将程序从浮点精度更改为双精度。 Nevertheless I start this routine by reading floating point numbers from a binary file. 不过,我通过从二进制文件读取浮点数来启动此例程。
bufz = alloc1float(nz);
for (i=0; i<nx; i++) {
nu = efread(bufz,sizeof(float),nz,vel);
for (k=0; k<nz; k++)
vn2[k][i] = bufz[k];
}
I proceed with calculations that shall be of double precision and write the calculated values into a file: 我将进行双精度计算,并将计算出的值写入文件中:
matlabfile=fopen("matlabfile","a+");
fprintf(matlabfile,"%d;%15.7e;%15.7e\n",l,amxs,amxr);
fclose(matlabfile);
(amxs and amxr are of size double, l is int and matlabfile is a filepointer) (amxs和amxr的大小是double的,l是int的,而matlabfile是filepointer的)
My question: How does C proceed with the input parameters of type float when the arithmetic is done with double precision and how does it round the result in the output? 我的问题:当算术以双精度完成时, C如何处理float类型的输入参数,以及如何在输出中舍入结果? Is it that easy as shown or do I miss something significantly? 如图所示,这很容易吗?还是我错过了很多东西?
EDIT: FILE *vel, *matlabfile; 编辑: FILE * vel,* matlabfile;
int main(int argc, char *argv[])
{
int i, nx, nz, k, nu, l;
double amxs, amxr;
double *buf;
double **vn2;
vn2 = alloc2double(nx,nz);
buf = alloc1float(nz);
/* read input binary file */
for (i=0; i<nx; i++) {
nu = efread(buf,sizeof(float),nz,vel);
for (k=0; k<nz; k++) vn2[k][i] = bufz[k];
}
Arithmetics with double precision arrays, variables and vn2...
// save output
matlabfile=fopen("matlabfile","a+");
fprintf(matlabfile,"%d;%15.7e;%15.7e\n",l,amxs,amxr);
fclose(matlabfile);
It doesn't. 没有。 It (implicitly) converts the double
into a float
and you lose precision. 它(隐式)将double
精度数转换为float
,您将失去精度。 It essentially chops off the least significant bits. 本质上,它会切掉最低有效位。
Sorry for the lack of concrete examples, but something like 9.223372036854775808
will become 9.223372037
. 抱歉,缺少具体示例,但类似9.223372036854775808
将变为9.223372037
。
A similar thing happens when you load your floats
into doubles
. 当您将floats
加载为doubles
时, floats
发生类似的情况。 It converts them into a different format. 它将它们转换为其他格式。 EDIT ... which works out fine. 编辑 ...这很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.