Rounding off
11 ビュー (過去 30 日間)
古いコメントを表示
1) Suppose I have two numbers, say 0.01234567 and 0.01234599 and I want Matlab to round off the numbers to give the number of d.p.'s such that the two numbers agree, in this case 0.012346, how might I do that?
2) What if I want to specify the number of d.p.'s manually?
Thanks.
0 件のコメント
回答 (3 件)
Walter Roberson
2012 年 1 月 17 日
Something similar to this:
V1 = 0.01234567;
V2 = 0.01234599;
mfactor = 10^(-ceil(log10(abs(V1 - V2))));
round(V1 * mfactor) / mfactor
round(V2 * mfactor) / mfactor
But not exactly this, because the above fails if the difference is 0, and is wrong for 1 (and probably is wrong for other powers of 10.) I also have not worked through all the details of the case where the two values are different signs.
There might also need to be an adjustment made for differences greater than 1.
MATLAB does not provide any specific function to round to decimal places, but there is an attempt at such a function in the File Exchange. I say "attempt" because binary floating point arithmetic is not able to exactly represent 0.1 so you can never round to exactly a decimal place.
0 件のコメント
sunil anandatheertha
2012 年 1 月 17 日
function [RoundedNumber] = mround(numbers,decimalPlace,option)
% mround: Manual Round
%This function takes the input 'numbers' in scalar or vector form AND depending on the required
%decimal place value, rounds it off.
% Example: number = 1.57657; decimalPlace = 4; Then, roundedNumber = 1.5765 or 1.5766, depending on
% floor or ceil functions respectively.
% sample usage: [RoundedNumber] = mround(34.6543546,3,'ceil')
format long
factor = 10^decimalPlace;
switch option
case 'round'
RoundedNumber = (round(numbers.*factor))/factor;
case 'floor'
RoundedNumber = (floor(numbers.*factor))/factor;
case 'ceil'
RoundedNumber = (ceil(numbers.*factor))/factor;
otherwise
RoundedNumber = (round(numbers.*factor))/factor;
end
fprintf('The rounded number is %12.8f\n',RoundedNumber)
end
1 件のコメント
Walter Roberson
2012 年 1 月 17 日
binary floating point arithmetic is not able to exactly represent 0.1 so you can never round to exactly a decimal place.
http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
Image Analyst
2015 年 2 月 4 日
Try round(x, N):
clc;
format long g; % Show all decimal places.
a6 = round(0.01234567, 6)
b6 = round(0.01234599, 6)
% Check for equality
a6 == b6
In the command window:
a6 = 0.012346
b6 = 0.012346
ans =
1
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!