Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct {
- double amp;
- double t;
- } data_t;
- static data_t **read_data(FILE *in, int *size);
- static double max_data(data_t **data, int size);
- static double linear_interpolation(data_t **data, int size, double target_amp);
- static void free_data(data_t **data, int size);
- int main(void);
- static data_t **read_data(FILE *in, int *size) {
- data_t **ret = NULL;
- char line[BUFSIZ];
- double amp, t;
- *size = 0;
- while (fgets(line, BUFSIZ, in)) {
- sscanf(line, "%lf%lf", &, &t);
- ret = (data_t **) realloc(ret, ++(*size) * sizeof(data_t *));
- ret[*size - 1] = (data_t *) malloc(sizeof(data_t));
- ret[*size - 1]->amp = amp;
- ret[*size - 1]->t = t;
- }
- return ret;
- }
- static double max_data(data_t **data, int size) {
- int i;
- double max, max_abs;
- max = data[0]->amp;
- max_abs = fabs(max);
- for (i = 1; i < size; i++)
- if (fabs(data[i]->amp) > max_abs) {
- max = data[i]->amp;
- max_abs = fabs(max);
- }
- return max;
- }
- static double linear_interpolation(data_t **data, int size, double target_amp) {
- int i;
- double a0, a1, t0, t1;
- a0 = data[0]->amp;
- t0 = data[0]->t;
- if (fabs(a0 - target_amp) < 1e-6) return t0;
- for (i = 1; i < size; i++) {
- if (a0 < target_amp && data[i]->amp > target_amp) {
- a0 = data[i - 1]->amp;
- t0 = data[i - 1]->t;
- a1 = data[i]->amp;
- t1 = data[i]->t;
- break;
- } else if (a0 > target_amp && data[i]->amp < target_amp) {
- a0 = data[i - 1]->amp;
- t0 = data[i - 1]->t;
- a1 = data[i]->amp;
- t1 = data[i]->t;
- break;
- }
- }
- return t0 + (target_amp - a0) / (a1 - a0) * (t1 - t0);
- }
- static void free_data(data_t **data, int size) {
- int i;
- for (i = 0; i < size; i++)
- free(data[i]);
- free(data);
- }
- int main(void) {
- data_t **data;
- int size;
- double max, time;
- data = read_data(stdin, &size);
- max = max_data(data, size);
- time = linear_interpolation(data, size, .2 * max);
- printf("max: %lf, 0.2 * max: %lf, time: %lf\n", max, .2 * max, time);
- free_data(data, size);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement