Self-test implementations.
133 {
134 std::cout << "Disclaimer: Because this is a randomized algorithm,"
135 << std::endl;
136 std::cout
137 << "it may happen that singular samples deviate from the true result."
138 << std::endl
139 << std::endl;
140 ;
141
142math::monte_carlo::Function
f;
143 math::monte_carlo::Function pdf;
144 double integral = 0;
145 double lower_bound = 0, upper_bound = 0;
146
147
148 f= [&](
double& x) {
return-x * x + 4.0; };
149
150 lower_bound = -2.0;
151 upper_bound = 2.0;
152 pdf = [&](double& x) {
153 if (x >= lower_bound && x <= -1.0) {
154 return 0.1;
155 }
156 if (x <= upper_bound && x >= 1.0) {
157 return 0.1;
158 }
159 if (x > -1.0 && x < 1.0) {
160 return 0.4;
161 }
162 return 0.0;
163 };
164
166 (upper_bound - lower_bound) / 2.0, f, pdf);
167
168 std::cout << "This number should be close to 10.666666: " << integral
169 << std::endl;
170
171
172 f= [&](
double& x) {
returnstd::exp(x); };
173
174 lower_bound = 0.0;
175 upper_bound = 1.0;
176 pdf = [&](double& x) {
177 if (x >= lower_bound && x <= 0.2) {
178 return 0.1;
179 }
180 if (x > 0.2 && x <= 0.4) {
181 return 0.4;
182 }
183 if (x > 0.4 && x < upper_bound) {
184 return 1.5;
185 }
186 return 0.0;
187 };
188
190 (upper_bound - lower_bound) / 2.0, f, pdf);
191
192 std::cout << "This number should be close to 1.7182818: " << integral
193 << std::endl;
194
195
196
197
198
199 f= [&](
double& x) {
returnstd::sin(M_PI * x) / (M_PI * x); };
200
201 pdf = [&](double& x) {
202 return 1.0 / std::sqrt(2.0 * M_PI) * std::exp(-x * x / 2.0);
203 };
204
206
207 std::cout << "This number should be close to 1.0: " << integral
208 << std::endl;
209}
double f(double x)
A function f(x) that will be used to test the method.
double integral_monte_carlo(const double &start_point, const Function &function, const Function &pdf, const uint32_t &num_samples=1000000)
Compute an approximation of an integral using Monte Carlo integration.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4