Why my code doesn't detect appropriate natural numbers?

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?

Respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 11 de En. de 2013
Editada: Azzi Abdelmalek el 11 de En. de 2013
1.00000000000000000001==1
the result is 1
The precision has a limit

4 comentarios

try this
a = input('Enter a number: ','s')
if ~isequal(a(1),'-') && any(ismember(a,'.'))==0
disp('Good!');
else
disp('No!');
end
3 -> Good! (correct)
1.000001 -> No! (correct)
2.00000 -> No! (incorrect)
Furthermore, variable "a" should not be a string (it is a requirement to ensure compatibility with other modules). I tried to use VPA but I couldn't create appropriate input. What is more, these aren't "one-line" methods.
I gave just a hint, you can make more analyze.
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

Iniciar sesión para comentar.

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.

Categorías

Productos

Etiquetas

Preguntada:

el 11 de En. de 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by