필터 지우기
필터 지우기

Rounding off

조회 수: 8 (최근 30일)
Richard
Richard 2012년 1월 17일
답변: Image Analyst 2015년 2월 4일
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.

답변 (3개)

Walter Roberson
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.

sunil anandatheertha
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
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
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

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

제품

Community Treasure Hunt

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

Start Hunting!

Translated by