testMaths.c 2.12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*******************************************************************************
 * This file is part of SWIFT.
 * Copyright (C) 2016 Matthieu Schaller (matthieu.schaller@durham.ac.uk)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 ******************************************************************************/

#include "../config.h"
#include "approx_math.h"
#include "vector.h"

#include <math.h>
Matthieu Schaller's avatar
Matthieu Schaller committed
25
#include <stdio.h>
26

27
int main(int argc, char *argv[]) {
28 29

  const int numPoints = 60000;
Matthieu Schaller's avatar
Matthieu Schaller committed
30

31
  for (int i = 0; i < numPoints; ++i) {
Matthieu Schaller's avatar
Matthieu Schaller committed
32 33

    const float x = 0.6f * (i / (float)numPoints) - 0.3f;
34 35 36 37
    const float exp_correct = expf(x);
    const float exp_approx = approx_expf(x);

    const float abs = fabs(exp_correct - exp_approx);
Matthieu Schaller's avatar
Matthieu Schaller committed
38 39 40
    const float rel =
        0.5f * fabs(exp_correct - exp_approx) / fabs(exp_correct + exp_approx);

41
    int error = 0;
42 43 44

    if (abs > 3e-6 && fabsf(x) <= 0.2) {
      printf("Absolute difference too large !\n");
45
      error = 1;
46
    }
47
    if (abs > 3e-7 && fabsf(x) <= 0.1) {
48
      printf("Absolute difference too large !\n");
49
      error = 2;
50 51 52 53
    }

    if (rel > 1e-6 && fabsf(x) <= 0.2) {
      printf("Relative difference too large !\n");
54
      error = 3;
55
    }
56
    if (rel > 3e-7 && fabsf(x) <= 0.1) {
57
      printf("Relative difference too large !\n");
58
      error = 4;
59 60
    }

61
    if (error > 0) {
Peter W. Draper's avatar
Peter W. Draper committed
62 63
      printf("%2d/%d: x= %f exp(x)= %e approx_exp(x)=%e abs=%e rel=%e\n", i,
             error, x, exp_correct, exp_approx, abs, rel);
64 65 66 67 68 69 70 71
      return 1;
    }
  }

  printf("\nAll values are consistent\n");

  return 0;
}