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 be able to test the input and display "The number you have entered is not an integer"
The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .
To determine whether a number n is even or odd you can use the function rem(n,2). If rem(n,2) equals 0 then the number is even, otherwise it is odd. One nice thing about Matlab is that your program will work fine, no matter how inefficient you wrote it.
You can use the mod
function, which returns the remainder after division. All integers are divisible by 1
. So a good test for non-integer would be
integerTest=~mod(value,1);
This returns 0
if value
is not an integer and 1
if it is. You can then use this as a conditional to reject non-integer user inputs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With