how to find the max no of decimal places in an array of numbers?

7 Ansichten (letzte 30 Tage)
tombola
tombola am 12 Dez. 2011
Hi, is there an easy way to find the max number of decimal places in an array.
So, if I have [2, 2.3, 6.44, 5.891, 7]
The answer will be 3 (from 5.891)?
I've spent a few hours trying to find an answer but everything I can do is a bit of a fudge.
Cheers,
Tom.

Antworten (1)

Jan
Jan am 12 Dez. 2011
No, there is no stable method. Consider this:
x = [2, 5.891, 7.000000000000001, 6.999999999999999];
format short
disp(x)
format long g
disp(x)
fprintf('%.16g ', x);
fprintf('\n');
Some decimal values cannot be represented exactly in binary format. Then it is a question of taste to decide how many decimals are existing. Example:
x = 0:0.1:1;
disp(x(4))
disp(x(4) - 0.3)
fprintf('%.16f\n', x(4));
A kind of solution: Round to a suiting number of decimals at first ( x = round(x / 1e5)*1e5 ), then use fprintf to create a string and count the trailing zeros. Of couse you will still get some repeated .9999... for some input. There is no way to avoid this.
  2 Kommentare
Jan
Jan am 12 Dez. 2011
tombola writes (copied from Answer to Comment):
Hi, thanks. The problem I have is I'm displaying graphs of some data.
What's on the y axis will have even spacing, but it will be like
0, .25, .5, .75, 1, 1.25 etc. or 0, .125, etc. or, basically any progression of evenly increasing numbers.
My clients like this, but want all numbers to have the same dp (whatever the max dp is), so I need to find it, then do a num2str.
Jan
Jan am 12 Dez. 2011
This is another problem than in the original question. It saves time for you and for the ones who want to answer, if you ask exactly the question, you want to be solved.
Assuming that "dp" is the number of decimal places, this problem allows to use the additional information, that you have the lower and upper limit and the number of steps. Then you can calculate the step width and use LOG10 to get the "width" of the changes.
If you set the YLabels manually, case for fixing the YLim values also. Otherwise an internal resizing like for the PRINT command might create ugly diagrams.

Melden Sie sich an, um zu kommentieren.

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by