Skip to content

Instantly share code, notes, and snippets.

@SebastianWilke
Last active October 18, 2020 23:52
Show Gist options
  • Save SebastianWilke/4e9507886eec21bd7014a6ac2888ee04 to your computer and use it in GitHub Desktop.
Save SebastianWilke/4e9507886eec21bd7014a6ac2888ee04 to your computer and use it in GitHub Desktop.
functions to calculate sin, cos, exp and pi in c
// 3.1415926535897932384626433832795028841971693993751058209749445923
#include <stdio.h>
#include <stdint.h>
double pi_series_representation (int N)
{
double result = 0.0;
int8_t sign = 1;
for (int n = 0; n <= N; ++n)
{
result += sign * (1.0 / (2 * n + 1));
sign = -sign;
}
return 4 * result;
}
int main ()
{
// still only gives 8 decimal places
// there has to be a better way to calculate pi
printf ("pi = %.20f\n", pi_series_representation (1000000000));
return 0;
}
#include <math.h>
#include <stdio.h>
#define DEG_TO_RAD(degree) ((degree) * M_PI / 180.0)
double cos_series_representation (double x, int N)
{
double result = 1.0;
double previous = 1.0; // first term of the sum
for (int n = 1; n <= N; ++n)
{
double factor = -(x * x) / ((2 * n - 1) * (2 * n));
double current = previous * factor;
result += current;
previous = current;
}
return result;
}
int main ()
{
for (int degree = 0; degree <= 360; degree += 15)
{
printf ("sin(%3d°) = %.9f\n", degree,
cos_series_representation (DEG_TO_RAD(degree), 100));
}
return 0;
}
// e = 2.7182818284590452353602874713526624977572470936999595749669676277
#include <stdio.h>
double exp_series_representation (double x, int N)
{
double result = 1.0;
double previous = 1.0; // first term of the sum
for (int n = 1; n <= N; ++n)
{
double factor = x / n;
double current = previous * factor;
result += current;
previous = current;
}
return result;
}
int main ()
{
printf ("exp(%.2f) = %.9f\n\n", 1.0,
exp_series_representation (1.0, 100));
printf ("exp(%.2f) = %.9f\n\n", 0.0,
exp_series_representation (0.0, 100));
printf ("exp(%.2f) = %.9f\n\n", -3.0,
exp_series_representation (-3.0, 100));
return 0;
}
#include <math.h>
#include <stdio.h>
#define DEG_TO_RAD(degree) ((degree) * M_PI / 180.0)
double cos_series_representation (double x, int N)
{
double result = x;
double previous = x; // first term of the sum
for (int n = 1; n <= N; ++n)
{
double factor = -(x * x) / ((2 * n) * (2 * n + 1));
double current = previous * factor;
result += current;
previous = current;
}
return result;
}
int main ()
{
for (int degree = 0; degree <= 360; degree += 15)
{
printf ("sin(%3d°) = %.9f\n", degree,
cos_series_representation (DEG_TO_RAD(degree), 100));
}
return 0;
}
@FranckRedery
Copy link

you are crazy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment