Rounding off

10 次查看(过去 30 天)
Richard
Richard 2012-1-17
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
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 中查找有关 Logical 的更多信息

标签

尚未输入任何标签。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by