Advertisement
cd62131

Amplitude

Jul 27th, 2014
546
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. typedef struct {
  5.   double amp;
  6.   double t;
  7. } data_t;
  8. static data_t **read_data(FILE *in, int *size);
  9. static double max_data(data_t **data, int size);
  10. static double linear_interpolation(data_t **data, int size, double target_amp);
  11. static void free_data(data_t **data, int size);
  12. int main(void);
  13. static data_t **read_data(FILE *in, int *size) {
  14.   data_t **ret = NULL;
  15.   char line[BUFSIZ];
  16.   double amp, t;
  17.   *size = 0;
  18.   while (fgets(line, BUFSIZ, in)) {
  19.     sscanf(line, "%lf%lf", &amp, &t);
  20.     ret = (data_t **) realloc(ret, ++(*size) * sizeof(data_t *));
  21.     ret[*size - 1] = (data_t *) malloc(sizeof(data_t));
  22.     ret[*size - 1]->amp = amp;
  23.     ret[*size - 1]->t = t;
  24.   }
  25.   return ret;
  26. }
  27. static double max_data(data_t **data, int size) {
  28.   int i;
  29.   double max, max_abs;
  30.   max = data[0]->amp;
  31.   max_abs = fabs(max);
  32.   for (i = 1; i < size; i++)
  33.     if (fabs(data[i]->amp) > max_abs) {
  34.       max = data[i]->amp;
  35.       max_abs = fabs(max);
  36.     }
  37.   return max;
  38. }
  39. static double linear_interpolation(data_t **data, int size, double target_amp) {
  40.   int i;
  41.   double a0, a1, t0, t1;
  42.   a0 = data[0]->amp;
  43.   t0 = data[0]->t;
  44.   if (fabs(a0 - target_amp) < 1e-6) return t0;
  45.   for (i = 1; i < size; i++) {
  46.     if (a0 < target_amp && data[i]->amp > target_amp) {
  47.       a0 = data[i - 1]->amp;
  48.       t0 = data[i - 1]->t;
  49.       a1 = data[i]->amp;
  50.       t1 = data[i]->t;
  51.       break;
  52.     } else if (a0 > target_amp && data[i]->amp < target_amp) {
  53.       a0 = data[i - 1]->amp;
  54.       t0 = data[i - 1]->t;
  55.       a1 = data[i]->amp;
  56.       t1 = data[i]->t;
  57.       break;
  58.     }
  59.   }
  60.   return t0 + (target_amp - a0) / (a1 - a0) * (t1 - t0);
  61. }
  62. static void free_data(data_t **data, int size) {
  63.   int i;
  64.   for (i = 0; i < size; i++)
  65.     free(data[i]);
  66.   free(data);
  67. }
  68. int main(void) {
  69.   data_t **data;
  70.   int size;
  71.   double max, time;
  72.   data = read_data(stdin, &size);
  73.   max = max_data(data, size);
  74.   time = linear_interpolation(data, size, .2 * max);
  75.   printf("max: %lf, 0.2 * max: %lf, time: %lf\n", max, .2 * max, time);
  76.   free_data(data, size);
  77.   return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement