今天遇到一个问题
猛地一看,简直对这个题嗤之以鼻,太简单了,毫无难度。
于是打出这样篇代码:
clc,clear
%% single
%单精度
singlePrecision=single(1./(1:10000000));
sum(singlePrecision)
%% double
%双精度
doublePrecision=1./(1:10000000);
sum(doublePrecision)
好了,结束了。
ans =
16.7929
ans =
16.6953
正准备关闭,突然,我好像看到了什么,,,,
不对啊,single类型求和比double类型求和结果大?
按正常分析,我们都知道,single位数少,运算的时候double能保存的后几位single保存不了,所以single会少计算一些数字,所以single类型的和应该小一些啊。难道是,,,我写错了?
我旁边的兄弟也写了一段几乎一模一样的代码,结果他运行的结果是:
ans =
16.1121559
ans =
16.695311365858508
What???
为了保险起见,我把他的代码拷到我的电脑上运行,把我的拷到他的电脑上运行,结果发现我的电脑的输出结果跟之前一样,他的电脑的输出结果跟之前也一样。
double类型相同而single类型不同,那这样应该就是single类型的问题了,我用doc命令查看了single类型的帮助文件,内容是极少的,如下
single
Convert to single precision
Syntax
B = single(A)
Description
B = single(A)
converts the matrix A
to single precision, returning that value in B
. A
can be any numeric object (such as a double
). If A
is already single precision, single
has no effect. Single-precision quantities require less storage than double-precision quantities, but have less precision and a smaller range.
The single
class is primarily meant to be used to store single-precision values. Hence most operations that manipulate arrays without changing their elements are defined. Examples arereshape
, size
, the relational operators, subscripted assignment, and subscripted reference.
You can define your own methods for the single
class by placing the appropriately named method in an @single
folder within a folder on your path.
Examples
a = magic(4);
b = single(a);
whos
Name Size Bytes Class
a 4x4 128 double array
b 4x4 64 single array
More About
See Also
Introduced before R2006a
没解决我的问题,我不禁好奇, 点进了Floating-Point Numbers,看完没有理解,于是我找到下面参考文献的部分
References
[1] Moler, Cleve, "Floating Points," MATLAB News and Notes, Fall, 1996. A PDF version is available on the MathWorks Web site at http://www.mathworks.com/company/newsletters/news_notes/pdf/Fall96Cleve.pdf
[2] Moler, Cleve, Numerical Computing with MATLAB, S.I.A.M. A PDF version is available on the MathWorks Web site at http://www.mathworks.com/moler/.
点进去是一个PDF,内容还是挺清晰的。
我想,这就解决了我的疑惑,原来,floating-point 算法确实是依赖于机器的,不同电脑就是不同的。
最终得出结论(重点部分了)
理论上说,它可以减少空间使用,但文档中提到使用它并不会提高运算速度,所以想提高速度不要用它,想保证计算精度不要用它。single根据机器不同,为了可移植性,尽量不要使用single。
后话:
我想看看到底是哪一部分的原因,于是我把代码分开:
%% single
%单精度
n=single(1./(1:10000000));
% singlePrecision=single(1./(1:10000000));
% sum(singlePrecision)
sumOfSingle=single(0);
for i=1:10000000
sumOfSingle=single(sumOfSingle)+n(i);
end
sumOfSingle
当我把sum换成用for循环求和的时候,结果变得貌似合理:15.4037。于是我就使用doc命令查看了sum的帮助文件,也并没有看到这是为什么。还请看到的各位大神指点。
附上环境:win10 64位+MATLAB 2016a 64位