Skip to content

Instantly share code, notes, and snippets.

@fionn
Last active March 28, 2017 18:21
Show Gist options
  • Save fionn/4853af5bc7ebc30bf0af447b3d6206e1 to your computer and use it in GitHub Desktop.
Save fionn/4853af5bc7ebc30bf0af447b3d6206e1 to your computer and use it in GitHub Desktop.
Calculate the Riemann sum of 1 + e^x for 0 < x < 1.
TARGET = riemann
all: $(TARGET)
$(TARGET): $(TARGET).cpp
g++ -Wall -Wextra -O2 $(TARGET).cpp -o $(TARGET)
#include <iostream>
#include <cmath>
using namespace std;
double f(double x)
{
return 1 + exp(x);
}
double s(double h = 0.000009)
{
double s = 0;
for(double x = 0; x < 1; x += h)
s += f(x);
return s * h;
}
double epsilon(double h = 0.000009)
{
return abs(s(h) - exp(1));
}
double small_h()
{
for(double h = 0.1; h > 0; h /= 2)
if(epsilon(h) <= 1e-5)
return 2 * h;
return -1;
}
int main()
{
double h = small_h();
cout.precision(7);
cout << "s = " << s(h) << endl;
cout << "ε = " << epsilon(h) << endl;
cout << "h = " << h << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment