更新:已解决
我在while的外面定义了marks和ArbitrageFreeInterpolater变量,再在循环中赋值获取参数,再赋值给这两个变量,结果就对了~~
第一次在CSDN上提问,C++新手,下面是我写的一个作业的一部分,卡在一个问题很久了,一直出不来结果,希望大神可以帮忙看看,多谢了!!
int main(int argc, char* argv[])
{
ifstream fin;
fin.open("/Users/gxy/Desktop/eurusd.txt",0);
if(!fin) {
cerr << "input file does not exist" << endl;
return 1;
}
double spot, rd, rf;
fin >> spot >> rd >> rf;
double mu = rd - rf;
std::cout << "-------------------Input------------------\n"
<< "spot = " << spot << std::endl
<< "rd = " << rd << std::endl
<< "rf = " << rf << std::endl
<< "t \t ATM \t MS25 \t RR25 \t MS10 \t RR10" << std::endl;
vector< pair > pillarSmiles;
vector kmin, kmax;
int a = 0;
while(!fin.eof()) {
double t;
double atmvol;
double ms25;
double rr25;
double ms10;
double rr10;
if (fin >> t >> atmvol >> ms25 >> rr25 >> ms10 >> rr10) {
cout << t << "\t" << atmvol << "\t" << ms25 << "\t" << rr25 << "\t" << ms10 << "\t" << rr10 << std::endl;
vector< pair > marks = input2Marks(spot, rd, rf, t, atmvol, ms25, rr25, ms10, rr10);
ArbitrageFreeInterpolator af(t, marks, spot, mu);
pillarSmiles.push_back( pair(t, af) );
std::cout<< "pillarSmiles[" << a <<"].second.Vol(1.3)= "<<pillarSmiles[a].second.Vol(1.3)<<std::endl; //test1
kmin.push_back(marks.front().first); // for plotting the charts only
kmax.push_back(marks.back().first);
}
std::cout<< "out of if pillarSmiles[" << a <<"].second.Vol(1.3)= "<<pillarSmiles[a].second.Vol(1.3)<<std::endl; //test2
a++;
}
ImpliedVol iv(pillarSmiles);
LocalVol lv(iv, spot, rd, rf);
ImpliedVol,LocalVol,Smile都是自定义的类,AbitrageFreeInterpolator是Smile的子类,声明如下:
class Smile
{
public:
virtual double Vol(double strike) const = 0;
};
class ImpliedVol
{
public:
ImpliedVol( const vector< pair > );
// linear interpolation in variance, along the strike line
double Vol(double t, double k) const;
double dVoldK(double t, double k) const {return (Vol(t, k+0.01) - Vol(t, k-0.01)) / 0.02; }
double dVoldT(double t, double k) const {return (Vol(t+0.005, k) - Vol(t, k)) / 0.005; }
double dVol2dK2(double t, double k) const {return (Vol(t, k+0.01) + Vol(t, k-0.01) - 2*Vol(t, k) ) / 0.01 / 0.01; }
private:
const vector< pair > pillarSmiles;
};
class ArbitrageFreeInterpolator : public Smile
{
public:
ArbitrageFreeInterpolator(double _t, const vector< pair >& _marks, double _S, double _mu);
virtual double Vol(double strike) const;
private:
vector< pair > marks; //M (k, sigma) input pairs;
double S; // Spot price;
double mu; // drift of spot;
double t; //time to maturity(in unit of year);
vector< pair > outputmarks; // N (k, c)pairs;
vector y2; // second derivatives;
};
Input文件内容如下:
1.25805 0.0100 0.0030
0.02 0.1550 0.0016 -0.0065 0.0050 -0.0111
0.04 0.1395 0.0016 -0.0110 0.0050 -0.0187
0.06 0.1304 0.0021 -0.0143 0.0067 -0.0248
......
想问一下main函数中我两处cout的测试结果(test1,test2)为什么不同,if里面cout出的结果是对的,出了if结果就不对了,哪里改变了,是因为参数是引用的问题吗,要怎么改呢?