Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Help! Rounding without using preset MATLAB functions

Subject: Help! Rounding without using preset MATLAB functions

From: Steven

Date: 20 Nov, 2010 22:40:04

Message: 1 of 12

Hi everybody,

I'm supposed to write a code that will round any values to a specified numeric placement, such as the tens, hundredths, etc... without using any built in functions such as 'round','ceil',etc.. I'm at a complete loss.

Say, for example I'm testing on a single value 10.23, and I wanted to round it to 10.2.

 I have no idea how to make MATLAB check to see if it should round up or down, or how to add or subtract the correct numbers to get to where I need it. It's one of those times where I'm pretty sure if I get one good brainwave I'll be able to get a lot more done, but for now, I'm just sitting here.

I suppose I'm essentially trying to write the 'round' 'ceil' and 'floor' functions from the ground up.

I really appreciate any advice!

Steve

Subject: Help! Rounding without using preset MATLAB functions

From: Miroslav Balda

Date: 20 Nov, 2010 23:19:04

Message: 2 of 12

"Steven " <stevenlwillis@gmail.com> wrote in message <ic9io4$792$1@fred.mathworks.com>...
> Hi everybody,
>
> I'm supposed to write a code that will round any values to a specified numeric placement, such as the tens, hundredths, etc... without using any built in functions such as 'round','ceil',etc.. I'm at a complete loss.
>
> Say, for example I'm testing on a single value 10.23, and I wanted to round it to 10.2.
>
> I have no idea how to make MATLAB check to see if it should round up or down, or how to add or subtract the correct numbers to get to where I need it. It's one of those times where I'm pretty sure if I get one good brainwave I'll be able to get a lot more done, but for now, I'm just sitting here.
>
> I suppose I'm essentially trying to write the 'round' 'ceil' and 'floor' functions from the ground up.
>
> I really appreciate any advice!
>
> Steve

Hi Steve,

You example for rounding to one decimal place may be solved by a command
      around1 = round(10*a)/10;

Mira

Subject: Help! Rounding without using preset MATLAB functions

From: Roger Stafford

Date: 20 Nov, 2010 23:34:04

Message: 3 of 12

"Steven " <stevenlwillis@gmail.com> wrote in message <ic9io4$792$1@fred.mathworks.com>...
> Hi everybody,
>
> I'm supposed to write a code that will round any values to a specified numeric placement, such as the tens, hundredths, etc... without using any built in functions such as 'round','ceil',etc.. I'm at a complete loss.
>
> Say, for example I'm testing on a single value 10.23, and I wanted to round it to 10.2.
>
> I have no idea how to make MATLAB check to see if it should round up or down, or how to add or subtract the correct numbers to get to where I need it. It's one of those times where I'm pretty sure if I get one good brainwave I'll be able to get a lot more done, but for now, I'm just sitting here.
>
> I suppose I'm essentially trying to write the 'round' 'ceil' and 'floor' functions from the ground up.
>
> I really appreciate any advice!
>
> Steve
- - - - - - - - - - -
  You could approximate the 'round' function with

 y = x - atan(tan(pi*x))/pi;

However, it does seem rather absurd allowing 'tan' and 'atan' if one is not allowed to use 'round'. Also it suffers a serious accuracy loss when x is near the halfway point between integers.

Roger Stafford

Subject: Help! Rounding without using preset MATLAB functions

From: Steven

Date: 20 Nov, 2010 23:36:03

Message: 4 of 12

>
> Hi Steve,
>
> You example for rounding to one decimal place may be solved by a command
> around1 = round(10*a)/10;
>
> Mira

Thanks for the response Mira!

However I am not allowed to use any preset functions such as round.

Steve

Subject: Help! Rounding without using preset MATLAB functions

From: Matt Fig

Date: 20 Nov, 2010 23:36:04

Message: 5 of 12

What functions are you allowed to use? If you cannot use FLOOR, CEIL, or ROUND, then can you use the string functions like SPRINTF and the like?

Subject: Help! Rounding without using preset MATLAB functions

From: Steven

Date: 20 Nov, 2010 23:46:04

Message: 6 of 12

"Matt Fig" <spamanon@yahoo.com> wrote in message <ic9m14$604$1@fred.mathworks.com>...
> What functions are you allowed to use? If you cannot use FLOOR, CEIL, or ROUND, then can you use the string functions like SPRINTF and the like?

Good point Matt,

Here is the exact wording in the "can/cannot" part of the assignment.

"3. At any point in this code you shouldn’t use any built-in functions (such as: round, ceil, floor, fix, max, min, …etc).
4. You can ONLY use (length, size, relational operators {< > ~=}, logical operators {|, &}, if, for, while and switch)."

-Steve

Subject: Help! Rounding without using preset MATLAB functions

From: Jan Simon

Date: 21 Nov, 2010 00:08:03

Message: 7 of 12

Dear Steven,

> I'm supposed to write a code that will round any values to a specified numeric placement, such as the tens, hundredths, etc... without using any built in functions such as 'round','ceil',etc.. I'm at a complete loss.
> Say, for example I'm testing on a single value 10.23, and I wanted to round it to 10.2.

This is my job according to:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/295019#791758

At first: From a scientifical point of view, the question cannot be solved. You cannot do *anything* in Matlab "without any built-in functions"! Even this calls built-in conversions:
  a = 10.23;
And even less: Starting Matlab calls built-in functions in matlabrc.m!
Therefore I'd reject the question completely, or aks the teacher to specify the list of forbidden functions explicitely --- any kind of "etc..." disables the possibility to create a valid answer.

But if you cannot convince your teacher from this scientific point of view, you *must* pretend a solution due to the absence of a valid solution.

Idea 1: Print the number to the screen. Hold a sheet of paper before the screen such, that you cannot see the not wanted figures.

Idea 2: Print the number to the command window and decrease the window width until the wnated number of figures is not visible anymore.

Idea 3: Print the number to a string (SPRINTF), search for the dot (FINDSTR) and delete the trailing characters.

These 3 ideas are equivalent to CEIL, not ROUND. At least the idea 3 could consider the value of the first cropped figure, but this means a lot of work e.g. for rounding '9.999999999999999999999'.

Idea 4: Let e.g. SPRINTF('%.4f') do the work for you.

Idea 5:
  x = 10.23
  y = ((x * 10) - rem(x * 10, 1)) / 10
  If REM is not allowed, use MOD.
  If MOD is not allowed, use:
    x - fix(x)
  If FIX is not allowed, use:
    x - double(uint64(x))
  If the TIMES operator ("*") is not allowed, simulate it by a SUM:
    y * 10 => sum(x(ones(1, 10))
  if SUM is not allowed, create a FOR loop:
    s = 0; for i = 1:10, s = s + x; end

Idea 6: Write a C-mex file. Unfortunately there is no ROUND in the standard C-libs. But there is a modulo operator, which can be used with idea 5.

Idea 7: EVAL does not call a function, it asks Matlab to do it:
  y = eval('round(x*10)/10')

Idea 8: Forget Matlab, do it with a pencil on paper. If your teacher complains, point to the fact, that this produces less CO2 and that your pencil needs less time to boot.

But finally consider that "rounding" is not well defined at all for floating point numbers with a limited precision, see:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/296914
(one of your collegues??)

Please feel free to invite your teacher to this discussion. I'd looking forward to argue if it is possible to find a serious answer to a silly question.
And please do not be impressed by such homework questions! Spend more time in learning how to use Matlab efficiently.

Kind regards, Jan

Subject: Help! Rounding without using preset MATLAB functions

From: Matt Fig

Date: 21 Nov, 2010 00:35:04

Message: 8 of 12

"Steven " <stevenlwillis@gmail.com> wrote in message Here is the exact wording in the "can/cannot" part of the assignment.
>
> "3. At any point in this code you shouldn’t use any built-in functions (such as: round, ceil, floor, fix, max, min, …etc).
> 4. You can ONLY use (length, size, relational operators {< > ~=}, logical operators {|, &}, if, for, while and switch)."
>
> -Steve

If we are to take such a list as inclusive, I wonder if the task can be done at all. Are we supposed to understand that we cannot even use arithmetic operations? WOW, good luck with that!

@Jan, no need for EVAL! ;-)
r = pi*exp(1); % example number to round to various places.
for n = 0:5
     t(n+1) = sscanf(sprintf(['%.',sprintf('%i',n),'f'],r),'%f');
end
t

Subject: Help! Rounding without using preset MATLAB functions

From: Jan Simon

Date: 21 Nov, 2010 00:46:03

Message: 9 of 12

Dear Steven,

> "3. At any point in this code you shouldn’t use any built-in functions (such as: round, ceil, floor, fix, max, min, …etc).
> 4. You can ONLY use (length, size, relational operators {< > ~=}, logical operators {|, &}, if, for, while and switch)."

Thanks for this unspecific specification. If "...etc." means all commands not included in 4., you cannot perform a rounding.
E.g. the FOR operation is useless if neither HORZCAT (also known as [ and ] ) nor COLON (also known as : ) is allowed.

Another idea:
  warning('off', 'my:clandestine:rounding');
  warning('my:clandestine:rounding', '%.3f', pi);
  disp(lastwarn);

And: You could do it on the bit-level, if you are allowed to use TYPECAST to convert the IEEE floating point number to 8 UINT8 values. Perhaps this helps:
  http://www.mathworks.com/matlabcentral/fileexchange/25326

Kind regards, Jan

Subject: Help! Rounding without using preset MATLAB functions

From: Jan Simon

Date: 21 Nov, 2010 01:12:03

Message: 10 of 12

Dear Matt,

> r = pi*exp(1); % example number to round to various places.
> for n = 0:5
> t(n+1) = sscanf(sprintf(['%.',sprintf('%i',n),'f'],r),'%f');
> end
> t

Whoops: TIMES, EXP, COLON, PLUS, HORZCAT, SUBSASGN, DISPLAY. These operators are not on the list, Matt.

Let's look on the effects of the floating point nature:
  sprintf('%.16g\n', t)
  >> 9
        8.5
        8.5399999999999999
        8.5397
        8.5397300000000001
@Steven: Please ask your teacher to define "rounding" exactly - of course without using the terms "number", "precision" and "nearest".

Good night, Jan

Subject: Help! Rounding without using preset MATLAB functions

From: Roger Stafford

Date: 21 Nov, 2010 01:37:04

Message: 11 of 12

"Steven " <stevenlwillis@gmail.com> wrote in message <ic9mjr$c4s$1@fred.mathworks.com>...
> ......
> Here is the exact wording in the "can/cannot" part of the assignment.
>
> "3. At any point in this code you shouldn’t use any built-in functions (such as: round, ceil, floor, fix, max, min, …etc).
> 4. You can ONLY use (length, size, relational operators {< > ~=}, logical operators {|, &}, if, for, while and switch)."
>
> -Steve
- - - - - - - - -
  Well, here's my idea for your problem that would avoid hopelessly long algorithms. It is easy to transform your problem over to one that involves converting a value x which is known to be greater than or equal to 1 to the nearest integer not greater than x, namely the floor of x, so we start there. (A negative x can have its sign changed. A non-negative x less than one will floor to 0.)

  As a first step you do something like the following:

n = 1;
t = 2;
while t<=x
 t = 2*t;
 n = n+1;
end

Now you have x pinned: t/2 = 2^(n-1) <= x < t = 2^n. That means if x were to be expanded as a binary fraction, the leftmost 1-bit is at the n-th position left of the binary point. Set y = t/2 and t = t/4.

  Then the next step is to test whether x <= y + t. If so, add t to y, otherwise not. Then divide t by 2 and subtract 1 from n. Repeat this process until you have encountered the binary point which you can tell by checking on n. The y at that point is your floored x.

  Nothing but inequalities and arithmetic operations are involved. This is basically converting a number to binary the hard way, starting at the high end and working your way down to the binary point.

Roger Stafford

Subject: Help! Rounding without using preset MATLAB functions

From: Greg Heath

Date: 22 Nov, 2010 06:01:09

Message: 12 of 12

On Nov 20, 8:37 pm, "Roger Stafford"
<ellieandrogerxy...@mindspring.com.invalid> wrote:
> "Steven " <stevenlwil...@gmail.com> wrote in message <ic9mjr$c4...@fred.mathworks.com>...
> > ......
> > Here is the exact wording in the "can/cannot" part of the assignment.
>
> > "3.   At any point in this code you shouldn’t use any built-in functions (such as: round, ceil, floor, fix, max, min, …etc).
> > 4. You can ONLY use (length, size, relational operators {< > ~=}, logical operators {|, &}, if, for, while and switch)."
>
> > -Steve
>
> - - - - - - - - -
>   Well, here's my idea for your problem that would avoid hopelessly long algorithms.  It is easy to transform your problem over to one that involves converting a value x which is known to be greater than or equal to 1 to the nearest integer not greater than x, namely the floor of x, so we start there.  (A negative x can have its sign changed.  A non-negative x less than one will floor to 0.)
>
>   As a first step you do something like the following:
>
> n = 1;
> t = 2;
> while t<=x
>  t = 2*t;
>  n = n+1;
> end
>
> Now you have x pinned: t/2 = 2^(n-1) <= x < t = 2^n.  That means if x were to be expanded as a binary fraction, the leftmost 1-bit is at the n-th position left of the binary point.  Set y = t/2 and t = t/4.
>
>   Then the next step is to test whether x <= y + t.  If so, add t to y, otherwise not.  Then divide t by 2 and subtract 1 from n.  Repeat this process until you have encountered the binary point which you can tell by checking on n.  The y at that point is your floored x.
>
>   Nothing but inequalities and arithmetic operations are involved.  This is basically converting a number to binary the hard way, starting at the high end and working your way down to the binary point.
>
> Roger Stafford

Excellent!

http://en.wikipedia.org/wiki/Binary_search_algorithm

Greg

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us