How do I test for integers in MATLAB?

前端 未结 7 1348
遥遥无期
遥遥无期 2021-01-04 00:55

I\'m writing a program that will calculate factorials of integers. However, the part I\'m stuck on is if someone enters a non-integer such as 1.3, I\'d like to

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 01:20

    Here is another variation (you can see it being used in ISIND function: edit isind.m):

    integerTest = ( x == floor(x) );
    

    On my machine, it is faster than the other proposed solutions:

    %# create a vector of doubles, containing integers and non-integers
    x = (1:100000)';                       %'
    idx = ( rand(size(x)) < 0.5 );
    x(idx) = x(idx) + rand(sum(idx),1);
    
    %# test for integers
    tic, q1 = ~mod(x, 1); toc
    tic, q2 = x==double(uint64(x)); toc
    tic, q3 = x==floor(x); toc
    
    %# compare results
    assert( isequal(q1,q2,q3) )
    

    Timings:

    Elapsed time is 0.012253 seconds.
    Elapsed time is 0.014201 seconds.
    Elapsed time is 0.005665 seconds.
    

提交回复
热议问题