Test the normcdf function against numerical integration of the pdf of the normal distribution.
这个总体上不存在什么难度,只需要在原先的基础上实现一个函数就好了。具体代码地址:对比视图(d71848d08f52555c17957ad173a192e8339551a8...522d1b37a228b768cff1026c8616a159b4af0809) · 云金杞/learn_cpp_series - Gitee.com
double normcdf(double x) {
DEBUG_PRINT("normcdf(" << x << ")");
if (x <= 0) {
return 1 - normcdf(-x);
}
double k = 1 / (1 + 0.2316419 * x);
double poly = hornerFunction(k,
0.0, 0.319381530, -0.356563782,
1.781477937, -1.821255978, 1.330274429);
double approx = 1.0 - 1.0 / ROOT_2_PI * exp(-0.5 * x * x) * poly;
return approx;
}
#include "NormalPDF.h"
#include <cmath>
NormalPDF::NormalPDF() {
v = 0;
}
double NormalPDF::evaluate(double x) {
static const double inv_sqrt_2pi = 0.3989422804014327;
return inv_sqrt_2pi * std::exp(-0.5 * x * x);
}
double NormalPDF::integral(double a, double b, int nPoints) {
double h = (b - a) / nPoints;
double x = a + 0.5 * h;
double total = 0.0;
for (int i = 0; i < nPoints; i++) {
double y = evaluate(x);
total += y;
x += h;
}
return h * total;
}
static void testNormcdfAndIntegralToInfinity() {
double x = 0.5;
double r1 = normcdf(x);
NormalPDF np;
double r2 = 1 - integralToInfinity(np, x, 100000);
ASSERT_APPROX_EQUAL(r1,r2, 0.001);
}
系统当前共有 481 篇文章