Round to nearest ones place value ex ante

조회 수: 2 (최근 30일)
BuMatlab
BuMatlab 2022년 9월 29일
답변: Steven Lord 2022년 9월 29일
Please excuse me if this as been addressed/answered in a previous post, but I have not found a solution to this in my searches.
I am trying to round a number to certain ones place values that are unknown ex ante.
For example, the following value is unkown at first:
randi([3700 3705])
Now, once that number is known, I would like to know if the random number is closer to 3700 or 3705. In addition, the values of 3700 and 3705 are unkown at first as well.
Seems simple, but I'm struggling with this one, so any help is much appreciated!

답변 (3개)

Eric Delgado
Eric Delgado 2022년 9월 29일
Lim_down = 3700;
Lim_up = 3706;
x = randi([Lim_down Lim_up])
x = 3704
Lim_center = mean([Lim_down, Lim_up]);
if x < Lim_center; fprintf("Closer to %.0f", Lim_down);
elseif x > Lim_center; fprintf("Closer to %.0f", Lim_up);
else; fprintf("In between...");
end
Closer to 3706

David Hill
David Hill 2022년 9월 29일
a=1400;
b=2600;
r=randi([a b]);
abs(r-a)<abs(r-b);

Steven Lord
Steven Lord 2022년 9월 29일
theRange = [3700 3705];
x = randi(theRange, 10, 1);
closer = interp1(theRange, theRange, x, 'nearest');
Let's show the results in a table for easy interpretation.
results = table(x, closer, 'VariableNames', ["Generated Number", "Closer Endpoint"])
results = 10×2 table
Generated Number Closer Endpoint ________________ _______________ 3701 3700 3701 3700 3700 3700 3702 3700 3705 3705 3702 3700 3705 3705 3701 3700 3700 3700 3704 3705

카테고리

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