Why my code doesn't detect appropriate natural numbers?
Show older comments
Welcome!
I try to create a program. I decided to cut an algorithm responsible for detecting natural numbers to exhibit my problem.
a = input('Enter a number: '):
if(a>0 && mod(a,1)==0)
disp('Good!');
else
disp('No!');
end
However, when value of a has more than 15 digits, ex. 1.00000000000000000001, my program responds to the request against the expectations ('Yes!' instead of 'No!'). Apparently, code lacks one line (after input, before condition) to function properly. What line is missing?
Answers (2)
Azzi Abdelmalek
on 11 Jan 2013
Edited: Azzi Abdelmalek
on 11 Jan 2013
1.00000000000000000001==1
the result is 1
The precision has a limit
4 Comments
Azzi Abdelmalek
on 11 Jan 2013
try this
a = input('Enter a number: ','s')
if ~isequal(a(1),'-') && any(ismember(a,'.'))==0
disp('Good!');
else
disp('No!');
end
Patryk Ulatowski
on 11 Jan 2013
Azzi Abdelmalek
on 11 Jan 2013
I gave just a hint, you can make more analyze.
Walter Roberson
on 11 Jan 2013
If it is for compatibility with other modules then you are receiving the value numerically and so cannot receive a 1.00000000000000000001 because that cannot be passed through.
If your code is the one that is going to be reading the input from the user, then validate it first as a string and the convert the string to numeric to be passed on.
a = input('Enter a number: ','s')
if regexp(a, '^\d+(\.0*)')
disp('Good!')
a = str2num(a);
else
disp('No!')
end
Walter Roberson
on 11 Jan 2013
1.00000000000000000001 and 1 are represented the same way in MATLAB.
Note that when you use input() and do not use the 's' option, anything typed in is evaluated before being returned, so of the user were to enter something like
exp(3)/pi
as the input, that would be evaluated numerically and the result returned from input(). If you do not want that, use the 's' option of input() so that the input is a string; then analyze the string.
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!