1
$\begingroup$

First of all: I'm a beginner with Mathematica.

  1. I'd like to define a function called Rounding which does the following:

    • if for $x = n+a, n \in \mathbb{N}, a\in [0,1)$ I have $a < 0.5$ then the function should round down to $n$. Otherwise it should round up to $n+1$.

    I did this:

     Rounding[x_] := If[x - Floor[x] < 0.5, Floor[x], Ceiling[x]]
    

    It works.

  2. I'd like to create a list LIST of random integers and THEN create a LIST2 which rounds the elements of LIST with my Rounding function.

    LIST = Table[RandomInteger[{-10,10}]/2, {i,1,10}]
    
    LIST2 = Table[Round[...]???
    

I tried choosing each element of LIST by using Part[LIST,{k,1,10}] but I don't get it.

$\endgroup$
  • $\begingroup$ It is a general question. Do we think that we are here to make somebody's homework? $\endgroup$ – Alexei Boulbitch Apr 9 '14 at 8:08
5
$\begingroup$

In this instance, I would make your Rounding function work just the way the built in Round function does, where it will thread over lists:

Round[{1, 1.3, 0.5, 1.7, 2}] === {1, 1, 0, 2, 2}

By adding the Listable attribute to Rounding you can accomplish the same thing:

Attributes[Rounding] = {Listable};
Rounding[x_] := If[x - Floor[x] < 0.5, Floor[x], Ceiling[x]];

Now

Rounding[{1, 1.3, 0.5, 1.7, 2}] === {1, 1, 1, 2, 2}

Then to round LIST using this function, you can use

LIST2 = Rounding[LIST]

EDIT to add: If you need to do it the boring way because it's a homework problem (;)), you can use Table to accomplish the same thing:

LIST2 = Table[Rounding[e], {e, LIST}]

In Table (and Do and even Sum) you can have the "iterator" (i.e., the last argument) range over the elements of a list directly, instead of having to index into the list, like so:

LIST2 = Table[Rounding[List[[i]]], {i, Length[LIST]}]

I think the former is easier to read, it's definitely easier to type, and best of all, it can be considerably faster to boot.

$\endgroup$
  • $\begingroup$ Hi - can I do it without Listable? I'm not allowed to use it yet =/ $\endgroup$ – K. L. Apr 9 '14 at 15:53
  • $\begingroup$ Great help, I thank you so much. $\endgroup$ – K. L. Apr 9 '14 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.