问题
I want to set precision for all element of a matrix. Below is what I did:
>>A
A =
0 1.0000 0 0 0 0
-137.0830 0 0 0 0 0
0 0 0 1.0000 0 0
365.5546 0 0 0 0 0
0 0 0 0 0 1.0000
365.5546 0 0 0 0 0
>> vpa(A,2)
ans =
[ 0, 1.0, 0, 0, 0, 0]
[ -144.0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 1.0, 0, 0]
[ 377.0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 1.0]
[ 377.0, 0, 0, 0, 0, 0]
The result is not my desire, it should be: -137.08, 365.55, 365.55 in the first column. Please help to suggest me how to get it. Thank you so much!
回答1:
You are not using vpa
correctly. From the docs:
vpa(x,d) uses at least d significant digits
Nota that it says at least. That is why you still get 377 when you only asked for 2 significant digits.
It seems that you don't know what significant digits are. From Wikipedia:
The significant figures of a number are digits that carry meaning contributing to its measurement resolution. This includes all digits except:
- All leading zeros;
- Trailing zeros when they are merely placeholders to indicate the scale of the number (exact rules are explained at identifying significant figures); and
- Spurious digits introduced, for example, by calculations carried out to greater precision than that of the original data, or measurements reported to a greater precision than the equipment supports.
So you want this
>> vpa(365.5546, 5)
ans =
365.55
Now, to be consistent, you need to find out what is the maximum of your matrix and compute the desired number of significant digits from there.
max_number = floor(log10(max(abs(A(:))+1)) + 1);
decimals = 2;
vpa(A, max_number + decimals)
Here, max_number
is the maximum number of integer digits that your matrix has, and decimals
is the number of decimal places that you want to have.
回答2:
The second input to vpa
is the number of significant digits which is not the same as the number of values after the radix point. The number -137.08
actually has five signficant digits so you'll want to use a second input of 5
vpa(A, 5)
% [ 0, 1.0, 0, 0, 0, 0]
% [ -137.08, 0, 0, 0, 0, 0]
% [ 0, 0, 0, 1.0, 0, 0]
% [ 365.55, 0, 0, 0, 0, 0]
% [ 0, 0, 0, 0, 0, 1.0]
% [ 365.55, 0, 0, 0, 0, 0]
回答3:
vpa(x,d)
:
d
is significant digits, not decimal places.
pvalue = vpa(-137.0830);
twopvalue = vpa(-137.0830,2);
% pvalue = -137.08299999999999840838427189738
% twopvalue = -144.0
If you want to get -137.08, 365.55, 365.55 in the first column. You can use roundn(A,-2)
roundn(A,-2)
ans =
0 1.0000 0 0 0 0
-137.0800 0 0 0 0 0
0 0 0 1.0000 0 0
365.5500 0 0 0 0 0
0 0 0 0 0 1.0000
365.5500 0 0 0 0 0
来源:https://stackoverflow.com/questions/42380463/set-precision-an-element-in-matlab-matrix