Find the number of digits after the decimal point in a number, please help!
조회 수: 50 (최근 30일)
이전 댓글 표시
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
Daniel Shub
2012년 11월 2일
This is essentially a duplicate of http://www.mathworks.com/matlabcentral/answers/52068-machine-precision-problem-in-code
채택된 답변
Azzi Abdelmalek
2012년 11월 2일
편집: Azzi Abdelmalek
2012년 11월 2일
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
Azzi Abdelmalek
2012년 11월 2일
편집: Azzi Abdelmalek
2012년 11월 2일
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
2012년 11월 2일
The point is that MATLAB cannot represent any of these numbers exactly. Therefore the number of decimal places is poorly defined.
추가 답변 (1개)
Chris Taylor
2023년 7월 26일
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!