How do I test for integers in MATLAB?

前端 未结 7 1392
遥遥无期
遥遥无期 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:27

    You can cast the value to an integer and back to a double and check the result against the original value:

    >> x = 1.3;
    >> x == double(uint64(x))
    
    ans =
    
         0
    
    >> x = 2;
    >> x == double(uint64(x))
    
    ans =
    
         1
    

    Interestingly, R.M.'s approach of using MOD runs faster in a loop and the above casting approach runs faster when vectorized:

    >> x = rand(100000, 1);
    >> tic; for ii = 1:100000; ~mod(x(ii), 1); end; toc;
    Elapsed time is 0.018380 seconds.
    >> tic; for ii = 1:100000; x(ii) == double(uint64(x(ii))); end; toc;
    Elapsed time is 0.383020 seconds.
    >> tic; ~mod(x, 1); toc;
    Elapsed time is 0.005299 seconds.
    >> tic; x == double(uint64(x)); toc;
    Elapsed time is 0.002971 seconds.
    

提交回复
热议问题