Last active
March 28, 2017 18:21
-
-
Save fionn/4853af5bc7ebc30bf0af447b3d6206e1 to your computer and use it in GitHub Desktop.
Calculate the Riemann sum of 1 + e^x for 0 < x < 1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
TARGET = riemann | |
all: $(TARGET) | |
$(TARGET): $(TARGET).cpp | |
g++ -Wall -Wextra -O2 $(TARGET).cpp -o $(TARGET) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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