gpt4 book ai didi

Matlab fwrite精度转换

转载 作者:行者123 更新时间:2023-12-01 23:29:57 26 4
gpt4 key购买 nike

我想以精度将一些数据写入二进制文件。数据最初是 double 精度。通过在 fwrite 之前调用 single 命令将数据转换为 single 和让 Matlab 在 中进行转换之间有什么区别fwrite 调用?

案例一

data1 % double precision
fwrite(fid,data1,'single');

案例二

data2=single(data1);
fwrite(fid,data2,'single');

在第二种情况下,Matlab 是否在写入 data2 之前对其进行了任何修改,因为它已经是 single 格式?写入两个文件的数据会有什么不同吗?

最佳答案

让我们试试这个:

data1 = 1.555555555555555555;
data2 = single(data1);

fid = fopen('C:\Some\Address\data1.bin', 'w');
fwrite(fid, data1, 'single');
fclose(fid);

fid = fopen('C:\Some\Address\data2.bin', 'w');
fwrite(fid, data2, 'single');
fclose(fid);

% Lets read them back (note that MATLAB stores them in a double-precision variable by default)
fid = fopen('C:\Some\Address\data1.bin', 'r');
data1 = fread(fid, 'single');
fclose(fid);
fid = fopen('C:\Some\Address\data2.bin', 'r');
data2 = fread(fid, 'single');
fclose(fid);

format long;
[data1 data2] % or use fprintf to see the values

ans =

1.555555582046509 1.555555582046509

您的问题:

In the 2nd case, is Matlab doing any modifications to data2 beforewriting it since it is already in single format ?

我不这么认为,但如果不知道 fwrite 的幕后发生了什么,我就无法自信。

Will there be any difference in data written to the two files ?

根据上面的测试我不相信,

关于Matlab fwrite精度转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66449675/

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