durbins.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include "local_proto.h"
  5. /* could probably use some cleanup/optimization */
  6. double *Cdhc_durbins_exact(double *x, int n)
  7. {
  8. static double y[2];
  9. double *xcopy, sumx = 0.0, sumx2 = 0.0, s2, *b, *c, *g, *z, sqrt2;
  10. int i, j;
  11. if ((b = (double *)malloc(n * sizeof(double))) == NULL) {
  12. fprintf(stderr, "Memory error in Cdhc_durbins_exact\n");
  13. exit(EXIT_FAILURE);
  14. }
  15. if ((c = (double *)malloc((n + 1) * sizeof(double))) == NULL) {
  16. fprintf(stderr, "Memory error in Cdhc_durbins_exact\n");
  17. exit(EXIT_FAILURE);
  18. }
  19. if ((g = (double *)malloc((n + 1) * sizeof(double))) == NULL) {
  20. fprintf(stderr, "Memory error in Cdhc_durbins_exact\n");
  21. exit(EXIT_FAILURE);
  22. }
  23. if ((z = (double *)malloc(n * sizeof(double))) == NULL) {
  24. fprintf(stderr, "Memory error in Cdhc_durbins_exact\n");
  25. exit(EXIT_FAILURE);
  26. }
  27. if ((xcopy = (double *)malloc(n * sizeof(double))) == NULL) {
  28. fprintf(stderr, "Memory error in Cdhc_durbins_exact\n");
  29. exit(EXIT_FAILURE);
  30. }
  31. sqrt2 = sqrt((double)2.0);
  32. for (i = 0; i < n; ++i) {
  33. xcopy[i] = x[i];
  34. sumx += x[i];
  35. sumx2 += x[i] * x[i];
  36. }
  37. s2 = sqrt((sumx2 - sumx * sumx / n) / (n - 1));
  38. for (i = 0; i < n; ++i) {
  39. xcopy[i] = (xcopy[i] - sumx / n) / s2;
  40. b[i] = 0.5 + Cdhc_normp(xcopy[i] / sqrt2) / 2.0;
  41. }
  42. qsort(b, n, sizeof(double), Cdhc_dcmp);
  43. for (i = 1; i < n; ++i)
  44. c[i] = b[i] - b[i - 1];
  45. c[0] = b[0];
  46. c[n] = 1 - b[n - 1];
  47. qsort(c, n + 1, sizeof(double), Cdhc_dcmp);
  48. for (j = 1; j <= n; ++j)
  49. g[j] = (n + 1 - j) * (c[j] - c[j - 1]);
  50. g[0] = (n + 1) * c[0];
  51. g[n] = c[n] - c[n - 1];
  52. for (i = 0; i < n; ++i) {
  53. z[i] = 0.0;
  54. for (j = 0; j <= i; ++j)
  55. z[i] += g[j];
  56. z[i] = (i + 1.0) / n - z[i];
  57. }
  58. qsort(z, n, sizeof(double), Cdhc_dcmp);
  59. y[0] = z[n - 1];
  60. y[1] = sqrt((double)n) * z[n - 1];
  61. #ifdef NOISY
  62. fprintf(stdout, " TEST7 DRB(N) =%10.4f\n", y[0]);
  63. #endif /* NOISY */
  64. free(b);
  65. free(c);
  66. free(g);
  67. free(xcopy);
  68. free(z);
  69. return y;
  70. }