Skip to content

Instantly share code, notes, and snippets.

@nlw0
Created November 18, 2018 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nlw0/7ee419b1e1c0fb11c5b5a1f6e0e35f81 to your computer and use it in GitHub Desktop.
Save nlw0/7ee419b1e1c0fb11c5b5a1f6e0e35f81 to your computer and use it in GitHub Desktop.
Exponential function benchmark in C
#include<stdio.h>
#include<math.h>
// thanks Joe from stackoverflow
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
//thanks Sun Microsystems and Naohiko Shimizu/Tokai University
double myexpm1(double x) {
double ln2_hi = 6.93147180369123816490e-01;
double ln2_lo = 1.90821492927058770002e-10;
double one = 1.0;
double Q[] = { 1.0,
-3.33333333333331316428e-02,
1.58730158725481460165e-03,
-7.93650757867487942473e-05,
4.00821782732936239552e-06,
-2.01099218183624371326e-07};
double hi = x - ln2_hi;
double lo = ln2_lo;
double k = 1;
x = hi - lo;
double c = (hi - x) - lo;
double hfx = 0.5 * x;
double hxs = x * hfx;
double R1 = one + hxs * Q[1]; double h2 = hxs * hxs;
double R2 = Q[2] + hxs * Q[3]; double h4 = h2 * h2;
double R3 = Q[4] + hxs * Q[5];
double r1 = R1 + h2 * R2 + h4 * R3;
double t = 3.0 - r1 * hfx;
double e = hxs * ((r1 - t) / (6.0 - x * t));
e = (x * (e - c) - c);
e -= hxs;
return one + 2.0 * (x - e);
}
double myexp(double x) {
double exm1 = myexpm1(x);
return exm1 + 1;
}
double calcerr(double x) {
double mye = myexp(x);
double refe = exp(x);
return mye - refe;
}
int main() {
double nn[] = {1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9};
for (int n=0; n<7; n++) {
double tic=get_time();
double err=0;
for(int i=0; i <= nn[n]; i++) {
double x = 0.4 + 0.6 * i/nn[n];
err = fmax(err, calcerr(x));
}
double toc = get_time();
printf("(%g, %f, %g),\n", nn[n], toc-tic, err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment