Created
May 5, 2018 13:29
-
-
Save PiotrWegrzyn/ce9b5d0f9d7097572ddf6de6a28a4d36 to your computer and use it in GitHub Desktop.
Calculating errors of both montecarlo and trapezoid integration based on precalculated real value.
This file contains hidden or 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 <cstdlib> | |
#include <time.h> | |
double f(double x) { | |
return x*x; | |
} | |
double monteCarlo(int start, int stop, double N) { | |
double avarageValue=0.0; | |
for (int i = 0; i < N; i++) avarageValue += f(rand() / (double)RAND_MAX * 8 + 2); | |
return (avarageValue/N)*(stop-start); | |
} | |
double integralTrapezoid(int start,int stop,double N) { | |
double dx = (stop - start) / N; | |
double S=0.0; | |
for (int i = 1; i < N; i++) { | |
S += ((f(start + (i*dx)) + f(start + ((i - 1)*dx)))*dx) / 2; | |
} | |
return S; | |
} | |
double calculateError(double real, double expected) { | |
return expected - real; | |
} | |
int main() { | |
srand(time(NULL)); | |
std::cout << "Monte Carlo: " << std::endl; | |
std::cout << calculateError(monteCarlo(2, 10, 10), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(monteCarlo(2, 10, 100), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(monteCarlo(2, 10, 1000), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(monteCarlo(2, 10, 10000), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(monteCarlo(2, 10, 1000000), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << "Trapezoid: " << std::endl; | |
std::cout << calculateError(integralTrapezoid(2, 10, 10), 330.0+(2.0/3.0)) << std::endl; | |
std::cout << calculateError(integralTrapezoid(2, 10, 100), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(integralTrapezoid(2, 10, 1000), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(integralTrapezoid(2, 10, 10000), 330.0 + (2.0 / 3.0)) << std::endl; | |
std::cout << calculateError(integralTrapezoid(2, 10, 100000), 330.0 + (2.0 / 3.0)) << std::endl; | |
system("pause"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment