截断matlab中的十进制数?

Mel*_*elB 5 matlab rounding

在MATLAB中是否有一种快速简便的方法来截断十进制数,例如超过4位数?

round()没有帮助,它仍在四舍五入.我必须在for循环中使用它,所以最快的方式是值得赞赏的.

感谢您的投入.

jod*_*dag 9

这是截断d小数点后的数字的一种方法.

val = 1.234567;
d = 4;
val_trunc = fix(val*10^d)/10^d
Run Code Online (Sandbox Code Playgroud)

结果

val_trunc =

   1.2345
Run Code Online (Sandbox Code Playgroud)

如果你知道这val是积极的,那么floor()将代替fix().

  • 根据我的基准(见我的答案),这是迄今为止最快的方法,+1 (2认同)

inf*_*ton 8

还有一个选择:

x = -3.141592653;
x_trun = x - rem(x,0.0001)

x_trun =

    -3.1415
Run Code Online (Sandbox Code Playgroud)

感谢gnovice的更新.

一般来说,对于n小数位:

x_trun = x - rem(x,10^-n)
Run Code Online (Sandbox Code Playgroud)

  • 如果你将`mod`改为`rem`,这应该适用于负数. (3认同)

Lui*_*ndo 5

如果5从最后一个想要保留的小数中减去,则截断就像舍入一样.

所以,要截断xn十进制数字使用

round(x - sign(x)*.5/10^n, n)
Run Code Online (Sandbox Code Playgroud)

(感谢@gnovice注意到需要sign(x)处理负数.)

例如,

format long
x = 3.141592653589793;
for n = 2:5
    result = round(x - sign(x)*.5/10^n, n);
    disp(result)
end
Run Code Online (Sandbox Code Playgroud)

   3.140000000000000
   3.141000000000000
   3.141500000000000
   3.141590000000000
Run Code Online (Sandbox Code Playgroud)

  • 零完全取决于您的[`format`](http://uk.mathworks.com/help/matlab/ref/format.html)设置,而不是舍入过程.您将面对与此处其他方法相同的输出,但Luis可能具有`format long` set. (2认同)

Wol*_*fie 5

当您要求最快的方法时,我已经汇总了当前在此处回答的前 3 种截断方法的快速基准。请看下面的代码。我增加了x要舍入的向量的大小,使用timeit计时功能。

function benchie()
    % Set up iteration variables
    K = 17;  n = 4;  T = zeros(K,3);
    for k = 1:K
        x = rand(2^k,1);
        % Define the three truncation functions
        LuisRound = @() round(x - 0.5/10^n, n);
        JodagFix = @() fix(x*10^n)/10^n;
        InfoRem = @() x - rem(x,10^-n);
        % Time each function
        T(k,1) = timeit(LuisRound);
        T(k,2) = timeit(JodagFix);
        T(k,3) = timeit(InfoRem);
    end
    % Plot results
    figure
    plot(2.^(1:K), T); legend('LuisRound', 'JodagFix', 'InfoRem');
    grid on; xlabel('number of elements in x'); ylabel('time taken');
end
Run Code Online (Sandbox Code Playgroud)

结果图可以在这里看到:

阴谋

根据这个测试,jodagfix建议的方法要快得多,所以你应该使用这样的东西来自定义截断函数到n小数位:

function y = trunc(x, n)
%% Truncate matrix/scalar x to n decimal places
    if nargin < 2; n = 0; end; % default to standard fix behaviour if no n given
    y = fix(x*10^n)/10^n;      % return value truncated to n decimal places
end
Run Code Online (Sandbox Code Playgroud)

测试:

>> trunc([pi, 10.45, 1.9], 4)
>> ans = [3.1415   10.4500    1.9000]
>> trunc([pi, 10.45, 1.9], 1)
>> ans = [3.1      10.4       1.9] 
Run Code Online (Sandbox Code Playgroud)