home *** CD-ROM | disk | FTP | other *** search
/ MacHack 1999 / MacHack 1999.toast / The Hacks / ReaderMouse / UtilityFunctions.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-05-23  |  1.5 KB  |  71 lines  |  [TEXT/CWIE]

  1. /*
  2.     created March 10th 1998 by Katherine Smith
  3. */
  4.  
  5. #include <math.h>
  6. #include <QuickDraw.h>
  7. #include <stdio.h>
  8. #include <DateTimeUtils.h>
  9. #include "UtilityFunctions.h"
  10.  
  11.  
  12. /* functions */
  13.  
  14. /* returns a floating point between lowBound and highBound with uniform distribution. */
  15. float UtilRandomFloat (float lowBound, float highBound)
  16. {
  17.     return (float)(Random() + 32768) / (65535.0 / (highBound - lowBound)) + lowBound;
  18. }
  19.  
  20. long UtilRandomLong (long lowBound, long highBound)
  21. {
  22.     return ((Random() + 32768) % (highBound - lowBound + 1)) + lowBound;
  23. }
  24.  
  25. void UtilSeedRandom (long seed)
  26. {
  27.     if (seed == 0) GetDateTime((unsigned long*)&qd.randSeed);
  28.     else qd.randSeed = seed;
  29.     printf("%d \n",qd.randSeed);
  30. }
  31.  
  32. float UtilEuclideanDistance (float x1, float y1, float x2, float y2)
  33. {
  34.     return sqrt ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
  35. }
  36.  
  37. void NormalizeVector (float *x, float *y)
  38. {
  39.     float length;
  40.     
  41.     length = UtilEuclideanDistance (0,0,*x,*y);
  42.     
  43.     if (length != 0)
  44.     {
  45.         *x /= length;
  46.         *y /= length;
  47.     }
  48. }
  49.  
  50. /* solves the Least Squares approximation to a linear fit of a set of points */
  51. void UtilLeastSquareLineApprox (float *x, float *y, long numPoints, float *slope, float *yIntercept)
  52. {
  53.     float    d;
  54.     float    sumXSq, sumX, sumY, sumXY;
  55.     int        i;
  56.     
  57.     sumXSq = 0; sumX = 0; sumY = 0; sumXY = 0;
  58.     
  59.     for (i = 0; i < numPoints; i++)
  60.     {
  61.         sumXSq    += x[i] * x[i];
  62.         sumX    += x[i];
  63.         sumY    += y[i];
  64.         sumXY    += x[i] * y[i];
  65.     }
  66.     
  67.     d = numPoints * sumXSq - (sumX * sumX);
  68.     
  69.     *slope = (1/d) * (numPoints * sumXY - sumX * sumY);
  70.     *yIntercept = (1/d) * (sumXSq * sumY - sumX * sumXY);
  71. }