C++ 偏导数计算中的分段误差
我试图计算函数C++ 偏导数计算中的分段误差,c++,scientific-computing,C++,Scientific Computing,我试图计算函数f(x,y)=x+yw.r.tx和y在(3,2)点处的偏导数。我编写了代码,但它给了我一个错误,名为分段错误(内核转储)。我不知道那是什么。有人能指出这有什么不对吗 #include<iostream> #include<cmath> #include<vector> using namespace std; class Der{ private: double f; // function value at x vecto
f(x,y)=x+y
w.r.tx
和y
在(3,2)
点处的偏导数。我编写了代码,但它给了我一个错误,名为分段错误(内核转储)
。我不知道那是什么。有人能指出这有什么不对吗
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
class Der{
private:
double f; // function value at x
vector <double> df; // derivative of function at x
public:
Der();
Der(vector <double>* v);
Der operator+(Der); // f + g
void print();
};
Der :: Der(){}
Der :: Der(vector <double>* v){
this->f = v->at(0);
for(int i=1; i < v->size(); i++){
this -> df[i-1] = v->at(i);
}
}
Der Der :: operator+(Der g){
Der h;
h.f = this->f + g.f;
for(int i=0; i< df.size(); i++){
h.df[i] = this->df[i] + g.df[i];
}
return h;
}
void Der :: print(){
cout<<"Function value at given point is : "<<f<<endl;
for(int i=0; i< df.size(); i++){
cout<<"Derivative at given point is : "<<df[i]<<endl;
}
}
int main()
{
Der f;
vector <double> t {3,1,0};
vector <double> k {2,0,1};
Der x(&t),y(&k);
f = x+y;
f.print();
}
#包括
#包括
#包括
使用名称空间std;
班长{
私人:
双f;//x处的函数值
向量df;//函数在x处的导数
公众:
Der();
Der(向量*v);
Der运算符+(Der);//f+g
作废打印();
};
Der::Der(){}
Der::Der(向量*v){
此->f=v->在(0)处;
对于(inti=1;isize();i++){
这->df[i-1]=v->at(i);
}
}
Der::operator+(Der g){
Der h;
h、 f=此->f+g.f;
对于(int i=0;idf[i]+g.df[i];
}
返回h;
}
void Der::print(){
cout在构造函数中,向量df
为空,但尝试使用
this -> df[i-1] = v->at(i);
这将导致未定义的行为,因为您正在访问空向量的边界之外。解决此问题的一种方法是将该行替换为以下内容:
df.push_back(v->at(i));
这将在每次调用时增加向量的大小
在Der Der::operator+(Der g){
中,您还有:
h.df[i] = this->df[i] + g.df[i];
具有与构造函数相同的错误。h.df为空。您可以使用以下方法修复该错误:
h.df.push_back(this->df[i] + g.df[i]);
也类似于@πάνταῥεῖ 在C++中,我们更喜欢通过指针引用常量引用:
Der :: Der(const vector <double>& v){
Der::Der(常量向量&v){
df
没有大小,但是你尝试这个->df[i-1]=v->at(i);
@drescherjm啊!我明白了。谢谢你指出。我实际上是个新手。你可以使用df.push_back(v->at(i));
instead@uuuuuuuuuu希望通过const
reference:Der::Der(const-vector&v)传递向量参数{
。还有Der Der::operator+(Der g){
应该返回*这个
而不是临时的。@uuuuuuuuu关于我的最后一点,我建议读一下:但是我不知道我得到了同样的错误。除了这个之外还有什么错误吗?这行有同样的问题:h.df[I]=this->[I]+g.df[I]
好的,我明白了。让我更正所有错误。谢谢。你可以使用std::vector::resize()
作为替代解决方案,而不是在循环前推回():因此,在for循环声明中for(int I=0;I
size ofdf
是0。所以,这个语句也是无效的。对吗?