Find the precision of a value

조회 수: 22 (최근 30일)
Konstantinos Tsitsilonis
Konstantinos Tsitsilonis 2017년 7월 4일
편집: Stephen23 2017년 9월 26일
Hello,
Is there a function in matlab that returns the precision of a number? for example, if I have a number 5.34 i want it to return 0.01, if I have a number 4 I want it to return 1 etc..
Thanks in advance for your answers,
  댓글 수: 2
Adam
Adam 2017년 7월 4일
Given that many double-precision numbers cannot be represented to an exact level of accuracy this would be problematic. e.g.
>> a = 5.34
a =
5.34
>> sprintf( '%0.20f', a )
ans =
'5.33999999999999990000'
You would want this to return 0.01 which may be reasonable, but actually the precision (to use your term) of the number is way smaller.
José-Luis
José-Luis 2017년 7월 4일
Your question might make sense if your number is stored as a string, which your using the fprintf tag suggests.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2017년 7월 4일
편집: Stephen23 2017년 7월 4일
No doubt there will be disagreements over what it means for floating point numbers, but here is one solution which provides the least unexpected output by converting to string, converting the last non-zero digit to 1 and the rest to 0. I do not claim that it is fast, but it does seem to be reasonably robust.
function p = getprecision(x)
f = 14-9*isa(x,'single'); % double/single = 14/5 decimal places.
s = sprintf('%.*e',f,x);
v = [f+2:-1:3,1];
s(v) = '0'+diff([0,cumsum(s(v)~='0')>0]);
p = str2double(s);
end
and tested:
>> getprecision(5.34)
ans = 0.010000
>> getprecision(5)
ans = 1
>> getprecision(53400)
ans = 100
Notes:
  1. keep in mind that 5.34 and 0.01 do not really exist in binary floating point numbers. See Adam's comment.
  2. '%g' is an obvious choice, but is actually more complicated because it can return fixed point values with trailing zeros.
  댓글 수: 1
Jan
Jan 2017년 7월 4일
+1: "the least unexpected output" is a nice definition of a "best solution".

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

José-Luis
José-Luis 2017년 7월 4일
Just in case your number is stored as a string:
bla = '5.14';
result = strsplit(bla,'.');
result = numel(result{2})
There are better (faster) ways to do this, but coffee calls.
  댓글 수: 2
Stephen23
Stephen23 2017년 7월 4일
편집: Stephen23 2017년 7월 4일
What about:
bla = '534000';
bla = '0.000045';
bla = '2463.00000';
José-Luis
José-Luis 2017년 7월 4일
Then a regex() could work.

댓글을 달려면 로그인하십시오.


James Tursa
James Tursa 2017년 7월 5일
편집: Stephen23 2017년 9월 26일

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by