Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <random>
- #include <fstream>
- class MonteCarlo{
- public:
- MonteCarlo(double begin,
- double end,
- size_t number,
- std::function<double(double)> function,
- std::function<double(double)> antiderivative) :
- begin_(begin), end_(end), number_(number),
- function_(function), antiderivative_(antiderivative), result_(0) {}
- void Calculate() {
- std::random_device rd;
- std::mt19937 gen(rd());
- std::uniform_real_distribution<> dis(begin_, end_);
- for (size_t i = 0; i < number_; ++i) {
- result_ += function_(dis(gen));
- }
- result_ *= (end_ - begin_)/number_;
- true_result_ = antiderivative_(end_) - antiderivative_(begin_);
- difference_ = fabs(true_result_ - result_);
- }
- double GetResult() {
- if (!calculated_) {
- Calculate();
- calculated_ = true;
- }
- return result_;
- }
- double GetDiff() {
- if (!calculated_) {
- Calculate();
- calculated_ = true;
- }
- return difference_;
- }
- double GetTrueResult() {
- if (!calculated_) {
- Calculate();
- calculated_ = true;
- }
- return true_result_;
- }
- private:
- double begin_;
- double end_;
- size_t number_;
- std::function<double(double)> function_;
- std::function<double(double)> antiderivative_;
- bool calculated_;
- double result_;
- double true_result_;
- double difference_;
- };
- double func(double x) {
- return cos(x);
- }
- double antiderivative(double x) {
- return sin(x);
- }
- int main() {
- auto file_name = "result.txt";
- std::ofstream file;
- file.open(file_name);
- for (int exp_num = 1; exp_num < 100; ++exp_num) {
- auto MCcalc = MonteCarlo(
- /* начало = У*/ 0,
- /* конец = */ 3,
- /* количество точек = */ 10000,
- /* функция = */ func,
- /* первообразная = */ antiderivative);
- MCcalc.Calculate();
- file << exp_num << ' ' << MCcalc.GetDiff() << std::endl;
- }
- file.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement