Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active October 22, 2024 18:46
Show Gist options
  • Save juanfal/2b9d94a665b6f730a79a84c98e2d62a6 to your computer and use it in GitHub Desktop.
Save juanfal/2b9d94a665b6f730a79a84c98e2d62a6 to your computer and use it in GitHub Desktop.
exp n terms 3 calls
// 02.exp.cpp
// juanfc 2024-10-22
// calculate the factorial directly by adding n terms
// of its series development
// Look at https://en.wikipedia.org/wiki/Taylor_series
// https://gist.github.com/juanfal/2b9d94a665b6f730a79a84c98e2d62a6
#include <iostream>
using namespace std;
int main()
{
double exp(double x, int n=10);
for (double x = 1; x < 100; x+=10)
cout << "exp(" << x << ")= " << exp(x) << endl;
return 0;
}
double exp(double x, int n=10)
{
double fact(int n);
double pot(double b, int exponent);
double s = 0;
for (int i = 1; i <= n; ++i)
s += pot(x, i)/fact(i);
return s;
}
double fact(int n)
{
double f = 1;
for (int i = 2; i <= n; ++i)
f *= i;
return f;
}
double pot(double b, int exponent)
{
double p = 1;
for (int i = 0; i < exponent; ++i)
p *= b;
return p;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment