Skip to content

Instantly share code, notes, and snippets.

@JakubGrobelny
Created November 5, 2019 23:56
Show Gist options
  • Save JakubGrobelny/fb876de982c334b0c7ae64bafad1d05a to your computer and use it in GitHub Desktop.
Save JakubGrobelny/fb876de982c334b0c7ae64bafad1d05a to your computer and use it in GitHub Desktop.
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
double fast_sin(double x)
{
const double x_pi = x / M_PI;
const double floor_x_pi = floor(x_pi);
const double sign4 = (long long)floor_x_pi % 2 == 0 ? -4.0 : 4.0;
return sign4 * (x_pi - ceil(x_pi)) * (x_pi - floor_x_pi);
}
int main(int argc, char* argv[])
{
if (argc < 3)
{
fprintf(stderr, "No argument specified\n");
return 1;
}
const int n = atoi(argv[2]);
if (!n)
{
fprintf(stderr, "Invalid size '%s'!\n", argv[2]);
return 1;
}
volatile double x = -(n/3);
if (!strcmp(argv[1], "error"))
{
double abs_error = 0.0;
for (int i = 0; i < n; i++)
{
abs_error += fabs(sin(x) - fast_sin(x));
x += 0.3;
}
abs_error /= (double)n;
printf("Average absolute error: %f\n", abs_error);
return 0;
}
volatile double* sins = malloc(sizeof(double) * n);
if (!sins)
{
fprintf(stderr, "Failed to allocate the array!\n");
return 1;
}
double (*f)(double);
if (!strcmp(argv[1], "sin"))
f = sin;
else if (!strcmp(argv[1], "fast"))
f = fast_sin;
else
{
fprintf(
stderr,
"Invalid argument. Options are 'sin' | 'fast' | 'error' \n"
);
return 1;
}
for (int i = 0; i < n; i++)
{
sins[i] = f(x);
x += 0.3;
}
free((double*)sins);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment