Find the number of digits after the decimal point in a number, please help!
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
SB
le 2 Nov 2012
Réponse apportée : Chris Taylor
le 26 Juil 2023
Say you have a number, x, and you want to find the number of digits after the decimal point. I know that in matlab, one way to do it would be to convert the number to a string and find the length from after the decimal point, but I think num2str has issues. How would you find the number of digits after the decimal point in a number then (the question is complicated by the fact that the numbers are floating point).
%
function y = decimalpoint(x)
x = abs(x); %in case of negative numbers
y = 0;
while (floor(x)~=x)
y = y+1;
x = x*10;
end
This code doesn't work for some cases, such as decimalpoint(11.111). How would I make the code work for all cases? I think recursion could be useful too, but probably not necessary.
1 commentaire
Daniel Shub
le 2 Nov 2012
This is essentially a duplicate of http://www.mathworks.com/matlabcentral/answers/52068-machine-precision-problem-in-code
Réponse acceptée
Azzi Abdelmalek
le 2 Nov 2012
Modifié(e) : Azzi Abdelmalek
le 2 Nov 2012
x=11.111
x = abs(x); %in case of negative numbers
n=0
while (floor(x*10^n)~=x*10^n)
n=n+1
end
8 commentaires
Azzi Abdelmalek
le 2 Nov 2012
Modifié(e) : Azzi Abdelmalek
le 2 Nov 2012
x=11.111*(1-eps)
x*10^4=1.1111e+05
floor(x*10^4)=111109
and
x*10^5= 1111100
I know it has something to do with the way Matlab codes floting point numbers. Errors caused by quantification
Daniel Shub
le 2 Nov 2012
The point is that MATLAB cannot represent any of these numbers exactly. Therefore the number of decimal places is poorly defined.
Plus de réponses (1)
Chris Taylor
le 26 Juil 2023
a = 11.111;
b = numdecpoints(a);
function f = numdecpoints(x)
i = -1;
X = 0;
while X ~= x
i = i + 1;
X = round(x, i);
end
f = i;
end
This seems to work, making use of MATLAB's round function. Not sure if it is the most efficient but seems to work for me. Simply compare the output of your original number and the number rounded to i decimal places. When the values match, i is the number of demical places in the orginal number.
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!