C 试图使用MAX和累积功能
C++ trying to use max and accumulate function
我是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
阅读std::accumulate
上的C 标准库文档将解决您的问题。但是,由于您对语言的新手,而STL对于初学者来说很难破译,因此如何阅读文档。
template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
std::accumulate
是一个通用函数,因此在通用类型T
上进行了模板。就您而言,T = double
。它需要两个输入迭代器first
和last
,以及一个类型T = double
的初始值init
。因此,以下是如何累积std::vector<double>
的一个示例。
std::vector<double> v = { 1., 2., 3. };
double result = std::accumulate(v.begin(), v.end(), 0.);
请注意,vector::begin
和vector::end
返回迭代器分别为容器的起点和结尾。
使用迭代器替换给accumulate
并提供初始值。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- <streamsize>C++ 中 numeric_limits::max() 的值
- 黑客级别的Mini-Max Sum
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 如何在Directwrite中获得给定字体的可用OpenType功能
- C 试图使用MAX和累积功能