home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / cenvi23.zip / PI.CMM < prev    next >
Text File  |  1996-01-10  |  2KB  |  99 lines

  1. /************************************************************************
  2.  * This is PI.CMM, (c) 1993 by LB (lbartho@uni2a.unige.ch)              *
  3.  * permission is granted to Brent S. Noorda to use this code            *
  4.  *       Calling sequence: CEnvi PI [optional number of digits]         *
  5.  ************************************************************************/
  6.  
  7. #define    DIGITSPERWORD   4        // 10^4 < sqrt(2^32)
  8. #define    BASE            10000
  9.  
  10. digits = 0;    // default
  11. words;         // global
  12.  
  13. main( argc, argv )
  14. {
  15.    if( argc == 2 )
  16.       digits = atoi(argv[1]);
  17.  
  18.    if ( 2 < argc  ||  digits < 1 )
  19.       Instructions();
  20.  
  21.    words = ((digits + DIGITSPERWORD - 1)/ DIGITSPERWORD) + 1;
  22.    pi[0] = 2;
  23.  
  24.    for( i = DIGITSPERWORD * words * 10 / 3, j = 2*i + 1; i >= 1; i--, j -= 2 )
  25.    {
  26.       if( i % 10 == 0 )
  27.          printf("[%d]\t\r", i );
  28.       muldiv( pi, i, j );
  29.       pi[0] += 2;
  30.    }
  31.  
  32.    carryup( pi );
  33.  
  34.    for( printf("%d.", pi[0] ), i = 1; i < words; print( pi[i++] ) );
  35.    printf("\n");
  36.  
  37.    return   0;
  38. }
  39.  
  40. muldiv( array, multiplicand, dividend )
  41. {
  42.    carry = 0;
  43.  
  44.    for( i = 0; i < words; i++ )
  45.    {
  46.       temp = array[i] * multiplicand + carry * BASE;
  47.       temp = ldiv( temp, dividend );
  48.       array[i] = temp.quot;
  49.       carry = temp.rem;
  50.    }
  51. }
  52.  
  53. carryup( array )
  54. {
  55.    for( i = words-1; i >= 0; i-- )
  56.    if( array[i] >= BASE )
  57.    {
  58.       array[i] = array[i] - BASE;
  59.       array[i-1]++;
  60.    }
  61. }
  62.  
  63. col = 0;
  64.  
  65. print( n )
  66. {
  67.    sprintf( format, "%%0%dd", DIGITSPERWORD );
  68.    sprintf( s, format, n );
  69.    for( i = 0; s[i] && digits--; i++ )
  70.    {
  71.       putchar( s[i] );
  72.       if( ++col % 5 == 0 )
  73.       {
  74.          putchar(' ');
  75.          if( col % 10 == 0 )
  76.          {
  77.             putchar(' ');
  78.             if( col == 50 )
  79.             {
  80.                col = 0;
  81.                printf("\n  ");
  82.             }
  83.          }
  84.       }
  85.    }
  86. }
  87.  
  88. Instructions()
  89. {
  90.    puts("\a")
  91.    puts(`PI.CMM - Determine PI to arbitrary accuracy`)
  92.    puts(``)
  93.    puts(`USAGE: CEnvi PI [digits]`)
  94.    puts(``)
  95.    puts(`WHERE: digits - number of decimal digits to calculate; minimum 1`)
  96.    puts(``)
  97.    exit(EXIT_FAILURE);
  98. }
  99.