《quantitative finance with cpp》阅读笔记12---正态分布累积分布函数的两种计算方法并对比结果
作者:yunjinqi   类别:    日期:2023-12-27 13:47:06    阅读:122 次   消耗积分:0 分    

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);
}


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/377
上一篇:《quantitative finance with cpp》阅读笔记11---用数值积分法计算从x到无穷大的定积分函数
下一篇:《quantitative finance with cpp》阅读笔记13---使用差值微分法求任意函数在某点处的导数