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
I just wanted to point out that the provided methods all test for whether the input is a Gaussian integer, meaning that the real and imaginary parts are both integers. If you need to care about the imaginary part then you need to deal with it separately.
For my applications, inputs with imaginary components shouldn't be considered a valid integer, so I have this:
function boolResult = fnIsInteger(input)
%validate input
if isempty(input)
error('Input cannot be empty')
elseif ~isnumeric(input)
error('Input must be numeric')
end
boolResult = (imag(input) == 0) & (round(input) == input);
end
Using b3.'s tests:
>> x = rand(100000, 1);
>> tic; for ii = 1:100000; ~mod(x(ii), 1); end; toc;
Elapsed time is 0.003960 seconds.
>> tic; for ii = 1:100000; fnIsInteger(x(ii)); end; toc;
Elapsed time is 0.217397 seconds.
>> tic; ~mod(x, 1); toc;
Elapsed time is 0.000967 seconds.
>> tic; fnIsInteger(x); toc;
Elapsed time is 0.003195 seconds.
The looped call is quite a bit slower mostly due to the function overhead. Replacing the arithmetic expression with ~mod(dataInput, 1) will make it only 50% faster than the code that checks for imaginary parts.