# Need help defining my own rounding function

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.

-
It is a general question. Do we think that we are here to make somebody's homework? –  Alexei Boulbitch Apr 9 at 8:08

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.

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