简体   繁体   English

强制MATLAB默认使用“单精度”?

[英]Forcing MATLAB to use `single` precision as default?

Is there a way to force MATLAB to use single precision as default precision? 有没有一种方法可以强制MATLAB使用single精度作为默认精度?

I have a MATLAB code, whose output I need to compare to C code output, and C code is written exclusively using floats , no doubles allowed. 我有一个MATLAB代码,需要将其输出与C代码输出进行比较,并且C代码仅使用floats编写,不允许使用doubles

You can convert any object A to single precision using A=single(A); 您可以使用A=single(A);将任何对象A转换为单精度A=single(A);

The Mathworks forums show that in your case: system-specific('precision','8'); 在您的情况下,Mathworks论坛显示: system-specific('precision','8'); should do it. 应该这样做。 Try this in the console or add at the top of your script. 在控制台中尝试此操作,或在脚本顶部添加。

Short answer: You can't. 简短的回答:不能。

Longer answer: In most cases, you can get around this by setting your initial variables to single. 更长的答案:在大多数情况下,可以通过将初始变量设置为single来解决此问题。 Once that's done, that type will (almost always) propagate down through your code. 一旦完成,该类型(几乎总是)将在您的代码中向下传播。 (cf. this and this thread on MathWorks). (请参阅MathWorks上的thisthis线程)。

So, for instance, if you do something like: 因此,例如,如果您执行以下操作:

>> x = single(magic(4));
>> y = double(6);
>> x * y

ans =

  4×4 single matrix

    96    12    18    78
    30    66    60    48
    54    42    36    72
    24    84    90     6

MATLAB keeps the answer in the lower precision. MATLAB会以较低的精度保留答案。 I have occasionally encountered functions, both built-in and from the FileExchange, that recast the output to be a double, so you will want to sprinkle in the occasional assert statement to keep things honest during your initial debugging (or better yet put the assertion as the first lines of any sub-functions you write to check the critical inputs), but this should get you 99% of the way there. 我偶尔会遇到一些内置和来自FileExchange的函数,这些函数会将输出重铸为双精度,因此您将不时使用assert语句,以在初始调试时保持诚实(或者最好放下断言)作为您编写的用于检查关键输入的任何子功能的第一行),但这应该可以使您获得99%的收益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM