C 试图使用MAX和累积功能

C++ trying to use max and accumulate function

本文关键字:功能 MAX      更新时间:2023-10-16

我是C 的新手,这是我尝试编写的第一个程序。在以下代码中,我想模拟选项的价格并计算其值。我遇到了累积功能的错误。

我已经尝试过std::maxstd::accumulate,但它们不正常。

#include <iostream>
#include <algorithm>
#include <cmath>
#include<random>
#include<numeric>
#include<vector>
using namespace std;
double mc(int S, int K, float r, float vol, int T, int sim, int N){
mt19937 rng;
normal_distribution<>ND(0,1);
ND(rng);
std::vector<double> s(sim);
double dt = T/N;
for(int i =0;i<sim;i++)
{
    std::vector<double> p(N);
    p[0]=S;
    for(int k = 0;k<N;k++)
    {
        double phi = ND(rng);
        p[i+1] = p[i]*(1+r*dt+vol*phi*sqrt(dt));
    }
    s[i] = max(p[N-1]-K,0);
}
        float payoff = (accumulate(s)/sim)*exp(-r*T);
        return payoff;
}
int main(){
    cout << mc(100,100,0.05,0.2,1,100,100) << endl;
    return 0;
}

错误:

> test1.cpp:26:21: error: no matching function for call to 'accumulate'
>     float payoff = (accumulate(s)/sim)*exp(-r*T);
>                     ^~~~~~~~~~ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/numeric:158:1:
> note: candidate function template not viable: requires 3 arguments,
> but 1 was provided accumulate(_InputIterator __first, _InputIterator
> __last, _Tp __init) ^ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/numeric:168:1:
> note: candidate function template not viable: requires 4 arguments,
> but 1 was provided accumulate(_InputIterator __first, _InputIterator
> __last, _Tp __init, _BinaryOperation __binary_op) ^ 2 errors generated.

编辑:修复了最大功能。它使用0.0而不是0

阅读std::accumulate上的C 标准库文档将解决您的问题。但是,由于您对语言的新手,而STL对于初学者来说很难破译,因此如何阅读文档。

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

std::accumulate是一个通用函数,因此在通用类型T上进行了模板。就您而言,T = double。它需要两个输入迭代器firstlast,以及一个类型T = double的初始值init。因此,以下是如何累积std::vector<double>的一个示例。

std::vector<double> v = { 1., 2., 3. };
double result = std::accumulate(v.begin(), v.end(), 0.);

请注意,vector::beginvector::end返回迭代器分别为容器的起点和结尾。

使用迭代器替换给accumulate并提供初始值。