home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 June / MacFormat 25.iso / Shareware City / Developers / kvikkalkul / kvik / runtime libs / kvikmath.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-21  |  1.5 KB  |  87 lines  |  [TEXT/MPS ]

  1. /** kvikmath.c
  2.  ** kvik math routines.
  3.  **
  4.  ** Written by and Copyright 1994 Asher Hoskins.
  5.  **
  6.  ** The author retains copyright on this implementation. Permission for
  7.  ** educational and non-profit use is granted to all. If you're planning to
  8.  ** make money with this or any code derived from it, check with the author
  9.  ** first.
  10.  **/
  11.  
  12. #include "kvikmath.h"
  13.  
  14. /** Convert string holding fractional part of number to kvik number format.
  15.  **/
  16.  
  17. kviknum str2kvik(char *n)
  18. {
  19.     int i = 4;
  20.     kviknum k = 0;
  21.     int power = 2000;
  22.  
  23.     while (i>0 && n[4-i] != '\0') {
  24.         k += (n[4-i] - '0') * power;
  25.         power /= 10;
  26.         i--;
  27.     }
  28.  
  29.     if (i == 0 && n[4] >= '5')
  30.         k++;
  31.  
  32.     return(k);
  33. }
  34.  
  35. /** Negate kvik number.
  36.  **/
  37.  
  38. kviknum negate(kviknum n)
  39. {
  40.     return(n | 0x8000);
  41. }
  42.  
  43. /** Convert kvik number to a double.
  44.  **/
  45.  
  46. double kvik2doub(kviknum n)
  47. {
  48.     int mult = 1;
  49.  
  50.     if (n & 0x8000) {
  51.         mult = -1;
  52.         n &= 0x7fff;
  53.     }
  54.  
  55.     return(n/20000.0*mult);
  56. }
  57.  
  58. /** Convert double to a kvik number.
  59.  **/
  60.  
  61. kviknum doub2kvik(double n)
  62. {
  63.     kviknum k = 0;
  64.  
  65.     if (n <= -1 || n >= 1)
  66.         return(OVERFLOW);
  67.  
  68.     if (n < 0) {
  69.         k = 0x8000;
  70.         n = -n;
  71.     }
  72.  
  73. /*
  74.     printf("without bodge: %f -> %d\n", n*20000.0, (kviknum)(n*20000.0));
  75.     printf("with bodge: %f -> %d\n", (n*200000.0+1.0)/10.0,
  76.         ((kviknum)(n*200000.0+1.0))/10);
  77. */
  78.  
  79.     /* The bodgery below is necessary because my elderly version of
  80.      * gcc is bugged. (e.g. 13578.0 (double) gets converted to 13577 (unsigned
  81.      * int)). Doing it this way avoids the problem. You may have a problem
  82.      * if your computer's default int is less than 4 bytes.
  83.      */
  84.     return(k | ((kviknum)(n*200000.0+1.0))/10);
  85. }
  86.  
  87.