Rounding off

19 visualizaciones (últimos 30 días)
Richard
Richard el 17 de En. de 2012
Respondida: Image Analyst el 4 de Feb. de 2015
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.

Respuestas (3)

Walter Roberson
Walter Roberson el 17 de En. de 2012
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 el 17 de En. de 2012
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 comentario
Walter Roberson
Walter Roberson el 17 de En. de 2012
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

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 4 de Feb. de 2015
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

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Aún no se han introducido etiquetas.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by