《quantitative finance with cpp》阅读笔记20---计算一系列点离原点的平均距离
作者:yunjinqi   类别:    日期:2024-01-01 13:44:08    阅读:429 次   消耗积分:0 分    

Write a function meanDistance which takes a pointer to a list of Pair objects and computes the mean distance of (x, y) to the origin.


实现起来比较容易,下面代码仅供参考:

class Pair {
public:
    double x;
    double y;
    Pair();
    Pair(double x, double y);
};

Pair::Pair() :
    x(0.0), y(0.0) {
}

Pair::Pair(double x, double y) :
    x(x), y(y) {
}

/*
Write a function meanDistance which takes a pointer to a list of Pair
objects and computes the mean distance of (x, y) to the origin.
*/

double meanDistance(list<Pair>* lp) {
    double sum = 0.0;
    double size = lp->size();
    for (Pair &p : *lp) {
        sum += pow(p.x * p.x + p.y * p.y, 0.5);
    }
    return sum/size;
}

void testMeanDistance() {
    Pair p1 = { 3,4 };
    Pair p2 = { 3,4 };
    list<Pair> ps = { p1,p2 };
    double sum = meanDistance(&ps);
    ASSERT_APPROX_EQUAL(sum, 5.0, 0.0001);
}


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/385
上一篇:《quantitative finance with cpp》阅读笔记19---反转列表元素的顺序
下一篇:《quantitative finance with cpp》阅读笔记21---极坐标转换成直角坐标