Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active October 23, 2024 12:50
Show Gist options
  • Save juanfal/99504b4df2590c909b91a7ead0e96c5c to your computer and use it in GitHub Desktop.
Save juanfal/99504b4df2590c909b91a7ead0e96c5c to your computer and use it in GitHub Desktop.
expr series with functions. Two ways
// 01.exp.cpp
// juanfc 2024-10-23
// expr series with functions. Two ways
// https://en.wikipedia.org/wiki/Taylor_series
// https://gist.github.com/juanfal/99504b4df2590c909b91a7ead0e96c5c
#include <iostream>
using namespace std;
int main()
{
double exp(double x, int n);
double exp(double x, float precision=0.001);
// testing the functions
for (float x = 0; x <= 50; x+=10) {
cout << "exp(" << x << ")= "
<< exp(x, 20) << endl;
cout << "exp(" << x << ")= "
<< exp(x) << endl;
}
return 0;
}
double exp(double x, int n)
{
double pot(double x, int n);
double fact(int n);
double s = 0; // result
for (int i = 0; i < n; ++i)
s += pot(x, i)/fact(i);
return s;
}
double exp(double x, float precision)
{
double pot(double x, int n);
double fact(int n);
double s = 0; // result
int i = 0;
double term = pot(x, 0)/fact(0);
do {
s += term;
++i;
term = pot(x, i)/fact(i);
} while (term > precision);
return s;
}
double pot(double x, int n)
{
double r = 1;
for (int i = 0; i < n; ++i)
r *= x;
return r;
}
double fact(int n)
{
double r = 1;
for (int i = 2; i <= n; ++i)
r *= i;
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment