Here's a rounding function I wrote a while ago that includes banker's
rounding as an option. I don't know if this is available elsewhere in
standard libraries and I often find that something I've written has already
been done, usually better, before.
However, I like my notational innovation where I specify the rounding by an
amount, e.g. "0.05 roundNums" rounds to the nearest 0.05 (or "nickel", in
US).
Regards,
Devon
roundNums=: 3 : 0"1 0
NB.* roundNums: round numbers y to precision x, e.g.
NB. 0.1 roundNums 1.23 3.14159 2.718 -> 1.2 3.1 2.7.
NB. Optional 2nd left argument is single letter specifying
NB. type of rounding: Up, Down, or Banker's. Default
NB. banker's rounding (round halves up or down depending on
NB. parity of next (scaled) digit) tends to randomize bias.
1 roundNums y
:
RT=. 'B' NB. Default to Banker's rounding
TO=. x NB. Precision to which to round.
if. (2=#x)*.1=L. x do. 'TO RT'=. x end.
scaled=. y%TO NB. For Banker's: round down if last digit even,
select. RT
case. 'B' do. RN=. 0.5*(0~:2|<.scaled)+.0.5~:1|scaled NB. up if odd.
case. 'D' do. RN=. (0.5=1|scaled){0 _0.5 NB. Round halves down.
case. 'U' do. RN=. 0.5 NB. Round halves up.
end.
TO*<.scaled+RN
NB.EG 2 2 4 4 -: 1 roundNums 1.5 2.5 3.5 4.5 NB. Banker's: odd up,
even down
NB.EG 2 3 4 5 -: (1;'U') roundNums 1.5 2.5 3.5 4.5 NB. round up
NB.EG 1 2 3 4 -: (1;'D') roundNums 1.5 2.5 3.5 4.5 NB. round down
)
On Sun, May 10, 2009 at 2:38 AM, Sherlock, Ric <[email protected]>wrote:
> > From: Martin Kreuzer
> > While fumbling around with base notation, I found
> > 5b34
> > 19
> > 5b35
> > 20
> > 5b36
> > 21
> > while I was waiting to see an error message for the second and third
> > case (using digits not in the set for this base, beyond 0 1 2 3 4).
> > This is puzzling me.
>
> Seems consistent to me.
> 5b36
> There are 6 "ones" (5^0) and 3 "fives" (5^1), that makes 21.
>
> Obviously you can get 21 using 5b41 too.
>
> > 2
> > To use verbs like "roundint" or "roundbanker" is there a module I
> > need to load, if so which one..?
>
> Yes you need to load the numeric script:
> load 'numeric'
>
> If you are looking for something that you think might be available in a
> script somewhere in the J base library, then the Find in Files utility can
> be useful:
>
> Edit | Find in Files
>
> Choose the "Folders" tab.
> Find what: roundbaker
> In folders: ~system
>
> Click "Find" button.
>
> In the results:
> Place your cursor in the line that you are interested in.
> Click "Open" button.
>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
>
--
Devon McCormick, CFA
^me^ at acm.
org is my
preferred e-mail
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm