Post Reply 
HP 12C Permutation and Combination
08-18-2017, 07:25 PM (This post was last modified: 08-18-2017 08:21 PM by Dieter.)
Post: #16
RE: HP 12C Permutation and Combination
(08-17-2017 09:57 PM)BartDB Wrote:  Your routines are likely to fail due to overflow if n is greater than 69, even if the final result is less than 1E100.

Sure. They use the factorial function which overflows at x=70.

(08-17-2017 09:57 PM)BartDB Wrote:  I have added to the Software Library routines for the 12C for Combination and Permutation that should work for most instances where the result is less than 1E100.

http://www.hpmuseum.org/forum/thread-8856.html

Ah, yes. This program seems to use a technique similar to that in the thread I linked to, i.e. it does the calculation by repeated multiplication.

However, this can be improved. ;-) You say that the result is rounded to the nearest integer (to correct roundoff errors). But as far as I can see the result is not rounded but truncated. So if the result happens to be, say, 6,999999999 it is returned as 6 and not 7. If you want to round you should add a small amount like 0,1 before the INTG.

As already said earlier, the roundoff problem in the nCr routine can be avoided (well, almost) if the divisor is counted up instead of down. This way the intermediate results are exact integers. The following program uses this technique. And it also distinguishes nPr and nCr by the sign of r: if r<0 then nCr is calculated, else nPr. If r=0 the result is 1 in both cases. ;-)

Code:
01 ENTER
02 CLX
03 x≤y?
04 GTO 31
05 R↓
06 CHS
07 x<>y
08 STO 2
09 x<>y
10 -
11 LstX
12 x≤y?
13 x<>y
14 x<>y
15 STO 0
16 1
17 STO 1
18 STO 3
19 RCL 0
20 x=0?
21 GTO 46
22 RCL 2
23 STO*3
24 RCL 1
25 STO/3
26 1
27 STO-0
28 STO+1
29 STO-2
30 GTO 19
31 R↓
32 STO 0
33 x<>y
34 STO 2
35 1
36 STO 3
37 RCL 0
38 x=0?
39 GTO 46
40 RCL 2
41 STO*3
42 1
43 STO-0
44 STO-2
45 GTO 37
46 RCL 3
47 GTO 00

Example:
25 [ENTER]  7  [R/S] => 2 422 728 000
25 [ENTER] –7 [R/S] => 480 700

BTW, the above program also gets 90 C 7, 101 C 6 and 70 C 8 right.
On the other hand it overflows at 325 C 167. But there is a way... cf. the thread I linked to earlier.
And I like your short nPr routine – maybe we should combine both versions. ;-)

Edit: I tried just that and used your nPr routine. This way the whole program would be down to 44 lines.
But it seems that nP0 is not calculated correctly, the result is n instead of 1. Could you please check that?

Dieter
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
HP 12C Permutation and Combination - Gamo - 08-15-2017, 04:54 AM
RE: HP 12C Permutation and Combination - Dieter - 08-18-2017 07:25 PM



User(s) browsing this thread: 1 Guest(s)