Counting the number of digits
이전 댓글 표시
Hi,
how can I compute the number of digits A=[12875] how can I get 5 as the number of digits in A?
댓글 수: 3
Jun Wei Ng
2017년 9월 22일
The number divided by 10 until it lower than 1, each time the number divided by 10 need to count 1 and at the end, you will get the digit as the times.
Walter Roberson
2017년 9월 22일
Fails on negative numbers because they are already lower than 1
Steven Lord
2021년 1월 29일
How many digits does A have in the code below?
A = Inf;
How many digits does B have?
B = NaN;
How about C?
C = 3+4i;
채택된 답변
추가 답변 (8개)
Oleg Komarov
2011년 7월 3일
To count integer part
ceil(log10(abs(A)))
Edit
floor(log10(abs(A)+1)) + 1
댓글 수: 4
Walter Roberson
2011년 7월 15일
Fails on [-1,1] and all exact powers of 10.
Jan
2011년 7월 15일
ceil(log10(abs(A) + 1)) ?
Walter Roberson
2011년 7월 15일
Fails on 0, Jan.
Over integral values:
ceil(log10(max(1,abs(A)+1)))
Over real numbers,
ceil(log10(max(1,abs(A)*(1+eps))))
I think.
It's also necessary to handle cases where A is integer-class.
For sake of clarifying the limitations and assumptions in each suggested method:
A = [-2456 -1.45 0 0.05 0.16 1.5 10 100 35465].';
y1 = ceil(log10(abs(A))); % fails on 0, subunity fractions, powers of 10
y2 = floor(log10(abs(A)+1)) + 1; % 0 has 1 digit? yes/no?
y3 = ceil(log10(max(1,abs(A)+1))); % 0 has 0 digits, but 0.05 and 0.16 both have 1 digit?
y4 = ceil(log10(max(1,abs(A)*(1+eps)))); % fails on powers of 10
y5 = numdigits(A); % where does this one fail?
table(A,y1,y2,y3,y4,y5)
function ndigits = numdigits(x)
% NDIGITS = NUMDIGITS(X)
% A simple convenience tool to count the number of digits in
% the integer part of a number. For complex inputs, the result
% is the number of digits in the integer part of its magnitude.
%
% X is a numeric scalar or array of any class or sign.
%
% Note that the integer 0 is considered to have zero digits.
% Consequently, for numbers on the interval -1<X<1, NDIGITS is 0.
ndigits = ceil(log10(abs(double(fix(x)))+1));
end
Will do the trick for all nonzero integers:
fix(abs(log10(abs(A))))+1
For a 10,000 iteration benchmark with some above answers:
Jaymin= 1.423717 seconds; Stephanie= 0.476135 seconds; Mine= 0.000878 seconds
If you don't expect 0s to appear, this is the fastest and most accurate method. Only works for decimals that satisfy -1<A<1.
댓글 수: 1
This doesn't actually provide meaningful results on the specified interval.
x = (-0.15:0.025:0.15).';
y1 = floor(log10(abs(x)+1))+1; % works for all integers (assumes 0 is 1 digit)
y2 = fix(abs(log10(abs(x))))+1; % works for nonzero integers
table(x,y1,y2)
Consider the case of abs(x) = 0.125. In what interpretation does this value have one digit?
Consider the case of abs(x) = 0.10. The naive interpretation of this value might suggest that it has either 1 or 2 digits (depending if you consider the leading integer 0). In reality, 0.1 is not exactly represented in floating point, so instead it's actually 0.999999999999999916 ... etc, or some similar approximation depending on how it was calculated. In base-2, 0.1 has as many digits as your floating-point approximation allows. If 0.125 has 1 digit, then no consistent interpretation would suggest that 0.10 has 2 digits.
As the utility for the fractional part of the number can now be ignored, the only meaningful difference between the two methods presented is the initial offset of 1 to avoid the singularity in log(x). At that point, the distinction between floor() and fix() can be ignored, since all its inputs will be positive.
Bear in mind that for practical use, we should be considering double(x) or something equivalent, otherwise both methods will fail if x is integer-class.
Jaymin
2012년 12월 13일
편집: Walter Roberson
2020년 5월 30일
Long, but it gets the job done.
numel(num2str(A))-numel(strfind(num2str(A),'-'))-numel(strfind(num2str(A),'.'))
댓글 수: 1
Walter Roberson
2020년 5월 30일
Fails on floor(pi*1e25)
fugue
2013년 5월 26일
numel(num2str(fix(abs(A))))
댓글 수: 1
Walter Roberson
2020년 5월 30일
Fails on floor(pi*1e25)
ARVIND KUMAR SINGH
2020년 5월 30일
0 개 추천
no_of_digits = numel(num2str(abs(A)));
댓글 수: 1
Walter Roberson
2020년 5월 30일
Fails on floor(pi*1e25)
Mayur Lad
2020년 10월 8일
편집: Walter Roberson
2020년 10월 8일
x=input('Enter number: ');
disp(x)
sum= 0;
while x > 0
t = mod(x,10);
sum= sum+1;
x = (x-t)/10;
end
fprintf('no of digit is:\t %d',sum)
댓글 수: 3
Walter Roberson
2020년 10월 8일
This code will not work for negative values.
For the value 0, this code will indicate that the number of digits is 0, but the number of digits for 0 should be 1.
manindra
2023년 1월 27일
If number is 0 or negative, the control doesn't even enter into the loop. Thats just a dumb question.
Walter Roberson
2023년 1월 27일
I am not clear as to what you are saying is "dumb" ?
Daniel Dalskov
2021년 1월 29일
I am using a simplified version of the below to determine whether I should try to represent a number as x*pi, x*sqrt(2), x*exp(1) or a fraction. In my case I only needed to check if there are more than are 14 digits, so no for-loop needed.
It basically finds the difference between the first and last non-zero number. Sign, decimal point and exponent are not included in the count.
a = [0,12e-17,1,10,21003, round(pi,3)*1e6, round(pi,5), round(pi,10), round(pi,10)*1e-3, round(pi*1e-5,10), pi, pi*1e307, pi*1e-314];
a = [a, -a];
for i=1:length(a)
b=abs(a(i)); % sign is not important for the number of digits, but feel free to add 0>sign(a(i)) to sd
if b < 3e-323 % depending on how precise you want to be
sd = 1; % could be changed to zero depending on your usecase
else
msd=floor(log10(b)); % most significant digit
lsd=-inf;
for dp=msd:-1:-323 % again depending on how precise you want to be, numbers really close to zero gets a little ify
if mod(b,10.^dp)==0
lsd=dp-1; % least significant digit
break
end
end
sd = msd-lsd; % number of digits
end
fprintf('%d significant digits\tin\t%s\n', sd, num2str(a(i), 16))
end
Aziz ur Rehman
2023년 6월 14일
The approach that i followed is in which i used a recursive function to compute the sum of digits of the integer provided such that the sum of A=[12345] is 15.
function x=digit_sum(input)
if input==0
x=0;
else
digit = rem(input,10);
input=(input-digit)/10;
x=digit+digit_sum(input);
end
end
You can see that for getting the 10th of the integer, i just divided the number by 10, and the remainder gave us the last digit, which in turn was added using a recursive function.
댓글 수: 1
Is this what you expected? I added one additional input to your function so it shows you the intermediary steps.
digit_sum(pi, true)
You can see the effect of the additional input on a problem where this function works:
digit_sum(12345, true)
The following behavior is what I expected for a non-finite input, since you are recursively calling digit_sum with Inf as the input each time. The same holds if you call digit_sum with NaN as input. I'm not showing the intermediate results, as I suspect the displaying of those steps would cause this code to time out in MATLAB Answers.
digit_sum(Inf, false)
Your code would also fail if input was a complex number.
function x=digit_sum(input, displaySteps)
if input==0
x=0;
else
digit = rem(input,10);
input=(input-digit)/10;
if displaySteps
fprintf("Digit is %g, input is %g\n", digit, input);
end
x=digit+digit_sum(input, displaySteps);
end
end
카테고리
도움말 센터 및 File Exchange에서 Numeric Types에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!