The Museum of HP Calculators

HP Forum Archive 20

[ Return to Index | Top of Index ]

RPN FLOOR and CEIL
Message #1 Posted by Werner on 27 Sept 2011, 5:37 a.m.

easy, short, no tests, valid for positive and negative arguments

1.using only FRC

CEIL(x) = x - FRC(FRC(x) - 1) FLOOR(x) = x - FRC(FRC(x) + 1)

(written 41C style, but easily portable)

*LBL"CEIL" ENTER FRC 1 - FRC - RTN

*LBL"FLOOR" ENTER FRC 1 + FRC - RTN

2.using MOD: (1 byte shorter for FLOOR..)

*LBL"CEIL" RCL X (or ENTER ENTER) -1 MOD - RTN

*LBL"FLOOR" RCL X 1 MOD - RTN

Cheers, Werner

      
Re: RPN FLOOR and CEIL
Message #2 Posted by Dieter on 27 Sept 2011, 8:28 a.m.,
in response to message #1 by Werner

Yes, as mentioned earlier, MOD can provide an elegant solution here. I especially like the idea with this double FRC since it can be used on virtually all RPN machines, but there is one caveat: There is a numeric pitfall for arguments close to zero.

For values so small that numerically 1x=1 the method will simply return x. For instance, x=1E-10 will return the correct result (1) on a 12-digit machine, but a 10-digit machine will return 1E-10. Otherwise your idea works well.

Dieter

            
Re: RPN FLOOR and CEIL
Message #3 Posted by Werner on 27 Sept 2011, 9:28 a.m.,
in response to message #2 by Dieter

*smack on the head*

You're absolutely right of course. Back to square one.

Werner

                  
Re: RPN FLOOR and CEIL
Message #4 Posted by Dieter on 28 Sept 2011, 7:58 a.m.,
in response to message #3 by Werner

The FRC method is fine for the programming contest since for r=<5000 there will be no fractional part less than frac(sqrt(4901)) = 0,00714. ;-)

For the record, here's another way to implement a CEIL resp. FLOOR function. It requires the same 7 bytes as yours, works for any argument and uses just two stack registers. However, SIGN is required. Or any other function that turns 0 < x < 1 into something between 1 and (less than) 2.

  INT
  LastX
  FRC
  X>0?     ; use X>0? for CEIL  or  X<0? for FLOOR
  SIGN
  INT
  +
BTW - the test before the SIGN function is not required because of the special way the HP-41 evaluates this function. ;-)

Dieter

                        
Re: RPN FLOOR and CEIL
Message #5 Posted by Werner on 28 Sept 2011, 8:18 a.m.,
in response to message #4 by Dieter

yes, that's what I used in my 41C program (found in another part of the forum - and lacking the second INT which is not needed for positive args.)

Some more CEIL stuff:

perfect function (i.e. LASTX contains X, no stack level used)
*LBL"CEIL"
 INT
 RUP
 X<> L
 X>Y?
 ISG Y
 LBL 00   (NOP)
 X<> L
 RDN
 END

and if we're not so picky: *LBL"CEIL" ENTER INT X<Y? ISG X END

if you put the code inline, you need a NOP after ISG X of course. (I tend to use LBL 00) BTW these work for all arguments.

Cheers, Werner


[ Return to Index | Top of Index ]

Go back to the main exhibit hall