c++ - C ++尝试使用max和accumulate函数
问题描述
我是 C++ 新手,这是我尝试编写的第一个程序。在下面的代码中,我想模拟期权的价格并计算其价值。我收到累积函数的错误。
我已经尝试过std::max
,std::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
解决方案
阅读 C++ 标准库文档std::accumulate
将解决您的问题。但是由于您是该语言的新手,而且 STL 对于初学者来说有点难以解读,这里是阅读文档的方法。
template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
std::accumulate
是一个泛型函数,所以它是在泛型类型上模板化的,T
. 在你的情况下,T = double
. 它需要两个输入迭代器,first
andlast
和一个初始值init
,类型为T = double
。所以,下面是一个关于如何积累std::vector<double>
.
std::vector<double> v = { 1., 2., 3. };
double result = std::accumulate(v.begin(), v.end(), 0.);
注意vector::begin
和vector::end
将迭代器分别返回到容器的开头和结尾。
将您的调用替换为accumulate
使用迭代器并提供初始值。
推荐阅读
- ruby - 何时使用关键字参数和选项哈希?
- ruby - 如何创建函数 .find_by_label(x),相当于 .find_by(label: x)?
- java - Junit 测试缺少的测试
- google-cloud-platform - Hive 到 GCP BigQuery 同步
- reactjs - 子组件中的 ondragend 事件调用父组件方法
- jquery - jQuery 更改淡出时间加载器屏幕
- css - 使用伪 :after-element 创建三角形颜色叠加
- kubernetes - K8s 服务无法ping通
- python - 基于验证损失和验证准确率保存 keras 模型
- angular - 类型 HTTPOriginal 不可分配给类型 Provider,插件安装后出现离子错误