Segmentation fault (core dumped) in class - c++

I see this error when running the below code:
Segmentation fault (core dumped)
I can't find the reason.
#ifndef DQMCBASE__H
#define DQMCBASE__H
const double pi=3.141592645;
#define rnd() ((double)rand())/ RAND_MAX
/**
* The basic walker class. This class serves the purpose of providing
* a structure that can be reused by inheriting.
*/
class DQMCWalker {
double _x; ///< dummy variable to implement basic 1D Harmonioscillator example.
This variable will be removed in future versions.
double _timeStep; ///< is the timestep in between to simultanious simulations
public:
DQMCWalker();
~DQMCWalker();
/**
* implements a normal distribution that can be used for the walking
* process defined in
* #see WalkNormal()
*
* #param variance the variance of the distribution.
* #param meanvalue the mean value of the distribution.
*
* #return A double distributed according to a normal distribution.
*/
double NormalDistribution(double variance, double meanvalue);
/**
* a virtual function that describes the walking process of the walker.
*
* #return returns 0, always.
*/
virtual int WalkNormal();
virtual double Potential();
virtual double Weight(double);
int Copy(DQMCWalker);
double SetDeltaT(double);
double GetDeltaT();
};
/* *
* The simulation class is a basic class that implements the basic features of walking, branching
* TODO
*/
template <class walker>
class DQMCSimulation {
walker* _walkers;
walker* _copies;
double _refE;
double _timeStep;
int _population;
int _max_walkers;
int _last_pop,_cur_pop,_nCopies;
public:
/**
* The constructor is used to define the simulation parameters of an instance. It takes two parameters,
* namely, the number of walkers and the time step in between two iterations.
*
* #param n the number of walkers used in the simulation.
* #param dt the time step in between two iterations.
*/
DQMCSimulation(int n, double dt);
~DQMCSimulation();
/**
* This function is used to perform one iteration. Every time this function is called
* a walkers are move according to the implementation of DQMCWalker::Walk(), next the
* reference energy is calculted according to the formula
* TODO
* and lastly, a birth-death process is performed.
*/
int Iterate();
double GetReferenceEnergy();
walker* WalkerArray();
};
#endif
up to here can be embeded into DQMCBase.h file
/* DQMCBase.cpp */
#include <iostream>
#include<math.h>
#include<stdlib.h>
#include<ctime>
//#include <DQMCBase.h>
using namespace std;
DQMCWalker::DQMCWalker() {
_timeStep=0.1;
_x=0.0;
}
DQMCWalker::~DQMCWalker() {
_x=0.0;
}
double DQMCWalker::NormalDistribution(double variance=1.0, double meanvalue=0.0) {
int samples=12;
double res = 0.0;
for(int i=0;i<samples;i++)
res +=rnd();
res = (res - samples*0.5)*sqrt(variance)+meanvalue;
return res;
}
int DQMCWalker::WalkNormal() {
_x+=NormalDistribution(1.0,0.0)*sqrt(_timeStep);
return 0;
}
double DQMCWalker::Potential() {
return 0.5*_x*_x;
}
double DQMCWalker::Weight(double refE) {
return exp(-(Potential()-refE)*_timeStep);
}
int DQMCWalker::Copy(DQMCWalker w) {
_x = w._x;
return 0;
}
double DQMCWalker::SetDeltaT(double timeStep) {
return (_timeStep = timeStep);
}
double DQMCWalker::GetDeltaT() {
return _timeStep;
}
template <class walker>
DQMCSimulation<walker>::DQMCSimulation(int n, double dt) {
_max_walkers = n;
_timeStep = dt;
_population = n;
_last_pop = _cur_pop = _population;
_walkers = new walker[2*n];
_copies = new walker[2*n];
for(int i=0;i<2*n; i++) {
_walkers[i].SetDeltaT(dt);
_copies[i].SetDeltaT(dt);
}
}
template<class walker>
DQMCSimulation<walker>::~DQMCSimulation() {
delete[] _walkers;
}
template <class walker>
int DQMCSimulation <walker>::Iterate() {
int i;
/* Make the walkers walk */
for(i=0;i<_cur_pop;i++)
_walkers[i].WalkNormal();
/* Calculating the reference energy */
double avg=0.0;
for(i=0;i<_cur_pop;i++)
avg += _walkers[i].Potential();
avg/=_cur_pop;
_refE =avg - (_cur_pop-_population)/(_population*_timeStep);
_last_pop = _cur_pop;
/* This is the part where walkers spawn and die */
int m,j;
_nCopies = 0;
for(i=0;i<_cur_pop;i++) {
m = floor(_walkers[i].Weight(_refE)+rnd());
if(m<3) m=3;
if(m==0) { /* The poor Walker dies */
if(_cur_pop>1) {
_walkers[i].Copy(_walkers[_cur_pop]);
i--, _cur_pop--;
} else {
cout << "WARNING :: Your population is dying!" << endl;
}
} else {
for(j=1;j<m;j++) {
_copies[_nCopies].Copy(_walkers[i]);
_nCopies++;
}
}
}
/* Adding the copies */
for(j=0;j<_nCopies; j++) {
_walkers[_cur_pop].Copy(_copies[j]);
_cur_pop++;
}
return 0;
}
template<class walker>
double DQMCSimulation<walker>::GetReferenceEnergy() {
return _refE;
}
template<class walker>
walker* DQMCSimulation<walker>::WalkerArray() {
return _walkers;
}
/*************************
* 1D Harmonic Oscillator
************************/
class DQMCHarmonic1DWalker : public DQMCWalker {
double _x;
public:
DQMCHarmonic1DWalker() {
_x=0.0;
}
int WalkNormal() {
double dt = sqrt(GetDeltaT());
_x+=NormalDistribution(1.0,0.0)*dt;
return 0;
}
double Potential() {
return 0.5*(_x*_x);
}
int Copy(DQMCHarmonic1DWalker w) {
_x = w._x;
return 0;
}
};
this is the main of the program
int main() {
srand ( time(NULL) );
int i,j, count;
double refE;
cout << "Hamonic 1D:" << endl;
DQMCSimulation<DQMCHarmonic1DWalker> simulation1(500,0.1);
refE = 0.0;
for(i=1; i<1000; i++) {
simulation1.Iterate();
refE += simulation1.GetReferenceEnergy();
if(i%50==0)
cout << refE/i << ", ";
}
return 0;
}

The first and easily noticeable problem is that You need to follow the Rule of Three/Five for DQMCSimulation class.

Related

Deep copy unsuccessful

might be a stupid question and if it is, let me know, I will delete it as soon as possible. The thing is I have to make a deep copy in class "Kambarys" (ignore mixed languages, I know I shouldn't do that). Program terminates after trying to call function second time. Probably the problem is my syntax in constructor copy, but I can't find the correct one anywhere. One of the requirements is to create langas, durys and kambarys in dynamic memory using "new" and delete windows vector and door in Kambarys destructor. Appreciate the help!
Requirements:
In the main method, use the new operator to create room k1, add windows and doors to it. Write a constructor Room (const Room & k) that would create a correct copy. In the method main, write another room k2. Calculate the length of the baseboards / wall area.
Perform the following steps: k2 = * k1; delete k1;
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
class Langas{
private:
float height;
float widht;
static int countL;
public:
Langas(float h, float w){
this->height=h;
this->widht=w;
countL++;
}
~Langas(){
--countL;
}
float getHeight(){
return height;
}
float getWidht(){
return widht;
}
static int getWindowCount(){
return countL;
}
};
class Durys{
private:
float heightD;
float widhtD;
static int countD;
public:
Durys(float hD, float wD){
this->heightD=hD;
this->widhtD=wD;
countD++;
}
~Durys(){
--countD;
}
float getHeightD(){
return heightD;
}
float getWidhtD(){
return widhtD;
}
static int getDoorCount(){
return countD;
}
};
class Kambarys{
private:
float heightK;
float widhtK;
float lenghtK;
public:
vector<Langas*> windows;
Durys* door;
Kambarys(float hK, float wK, float lK){
this->heightK=hK;
this->widhtK=wK;
this->lenghtK=lK;
}
Kambarys(const Kambarys &k){
this->door=k.door;
this->windows=k.windows;
heightK=k.heightK;
widhtK=k.widhtK;
lenghtK=k.lenghtK;
}
~Kambarys(){
door=NULL;
for(int i=0; i<windows.size(); i++){
delete windows[i];
}
windows.clear();
delete door;
}
float getHeightK(){
return heightK;
}
float getWidhtK(){
return widhtK;
}
float getLenghtK(){
return lenghtK;
}
void addWindow(Langas* w){
windows.push_back(w);
}
void addDoor(Durys *d){
door=d;
}
};
float countWallPlot(Kambarys* k){
float cWPlot=(2*k->getLenghtK()*k->getHeightK())+(2*k->getWidhtK()*k->getHeightK());
for(int i=0; i<k->windows.size(); i++){
cWPlot-=((k->windows[i]->getHeight()))*(k->windows[i]->getWidht());
}
cWPlot-=((k->door->getHeightD()))*(k->door->getWidhtD());
return cWPlot;
}
float countLenght(Kambarys* k){
float floorL=(k->getLenghtK()*k->getWidhtK()*2);
floorL-=(k->door->getWidhtD());
return floorL;
}
int Langas::countL=0;
int Durys::countD=0;
int main(){
Langas *langas1=new Langas(3.4, 1.2);
Durys *durys=new Durys(3.1, 1.5);
Langas *langas2=new Langas(6.4, 1.5);
Kambarys *k=new Kambarys(30.4, 40.1, 50.1);
Kambarys *k2=k;
k->addWindow(langas1);
k->addWindow(langas2);
k->addDoor(durys);
cout<<countWallPlot(k)<<" "<<countLenght(k)<<endl;
cout<<"Window count "<<Langas::getWindowCount()<<", door count "<<Durys::getDoorCount()<<endl;
k2=k;
delete k;
cout<<countWallPlot(k2)<<" "<<countLenght(k2)<<endl;
cout<<"Window count "<<Langas::getWindowCount()<<", door count "<<Durys::getDoorCount()<<endl;
}
You have to allocate memory for k2 and copy the object, not the pointer.
You have to allocate memory in the copy constructor and copy assignment operator.
door=NULL; before delete door; would skip the delete and cause a memory leak.
windows.clear(); is not necessary in the destructor. Keep your code simple.
EDIT: After you added "Perform the following steps: k2 = * k1; delete k1;" I made k2 an object, not a pointer.
#include <iostream>
#include <vector>
class Langas {
private:
float height;
float width;
static int count;
public:
Langas(float h, float w): height(h), width(w) {
++count;
}
~Langas() { --count; }
float getHeight() const { return height; }
float getWidht() const { return width; }
static int getWindowCount() { return count; }
};
class Durys {
private:
float height;
float width;
static int count;
public:
Durys(float h, float w): height(h), width(w) {
++count;
}
~Durys() { --count; }
float getHeight() const { return height; }
float getWidth() const { return width; }
static int getDoorCount() { return count; }
};
class Kambarys {
private:
float height;
float width;
float length;
public:
std::vector<Langas *> windows;
Durys *door = nullptr;
Kambarys(float hK, float wK, float lK): height(hK), width(wK), length(lK) {}
Kambarys(const Kambarys &k): height(k.height), width(k.width), length(k.length), windows(), door(k.door ? new Durys(k.door->getHeight(), k.door->getWidth()) : nullptr) {
for (const auto window : k.windows) {
windows.emplace_back(new Langas(window->getHeight(), window->getWidht()));
}
}
Kambarys &operator=(const Kambarys &k) {
door = k.door ? new Durys(k.door->getHeight(), k.door->getWidth()) : nullptr;
for (const auto window : k.windows) {
windows.emplace_back(new Langas(window->getHeight(), window->getWidht()));
}
height = k.height;
width = k.width;
length = k.length;
return *this;
}
~Kambarys() {
for (auto window : windows) {
delete window;
}
delete door;
}
float getHeight() const { return height; }
float getWidth() const { return width; }
float getLength() const { return length; }
void addWindow(Langas *w) { windows.emplace_back(w); }
void addDoor(Durys *d) { door = d; }
};
float countWallPlot(const Kambarys &k) {
float cWPlot = 2 * k.getLength() * k.getHeight() + 2 * k.getWidth() * k.getHeight();
for (const auto window : k.windows) {
cWPlot -= window->getHeight() * window->getWidht();
}
cWPlot -= k.door->getHeight() * k.door->getWidth();
return cWPlot;
}
float countLength(const Kambarys &k) {
float floor = k.getLength() * k.getWidth() * 2;
floor -= k.door->getWidth();
return floor;
}
int Langas::count = 0;
int Durys::count = 0;
int main() {
Langas *langas1 = new Langas(3.4, 1.2);
Durys *durys = new Durys(3.1, 1.5);
Langas *langas2 = new Langas(6.4, 1.5);
Kambarys *k = new Kambarys(30.4, 40.1, 50.1);
Kambarys k2(*k);
k->addWindow(langas1);
k->addWindow(langas2);
k->addDoor(durys);
std::cout << countWallPlot(*k) << " " << countLength(*k) << std::endl;
k2 = *k;
std::cout << "Window count " << Langas::getWindowCount() << ", door count " << Durys::getDoorCount() << std::endl;
delete k;
std::cout << countWallPlot(k2) << " " << countLength(k2) << std::endl;
std::cout << "Window count " << Langas::getWindowCount() << ", door count " << Durys::getDoorCount() << std::endl;
}

Pass a function of object of any type to another object in C++

I'm creating a node system (similar to eg. UE4 or Blender's Cycles) in which i can create nodes of different types and use them later. At the moment I have 2 classes of nodes with output functions like these:
class InputInt
{
public:
int output()
{
int x;
std::cin>>x;
return x;
}
};
class RandomInt
{
public:
int rand10()
{
int x;
x = rand()%10;
return x;
}
int rand100()
{
int x;
x = rand()%100;
return x;
}
};
I don't pass anything to these nodes. Now I want to create a node which takes and output function from and object of one of above classes. Here is how I implemented it to use InputInt node only:
class MultiplyBy2
{
typedef int (InputInt::*func)();
func input_func;
InputInt *obj;
public:
MultiplyBy2(InputInt *object, func i): obj(object), input_func(i) {}
int output()
{
return (obj->*input_func)()*2;
}
};
Having this I can create and use object of MultiplyBy2 in main() and it works perfectly.
int main()
{
InputInt input;
MultiplyBy2 multi(&input, input.output);
std::cout<<multi.output()<<std::endl;
}
It doesn't obviously work for object of RandomInt as I have to pass *InputInt object to MultiplyBy2 object. Is there a way to make MultiplyBy2 take any kind of an object with its output function eg. like this?
int main()
{
RandomInt random;
MultiplyBy2 multi2(&random, random.rand10);
std::cout<<multi2.output()<<std::endl;
}
An alternative approach, using a common base class with virtual methods:
#include <iostream>
struct IntOp {
virtual int get() = 0;
};
struct ConstInt: IntOp {
int n;
explicit ConstInt(int n): n(n) { }
virtual int get() override { return n; }
};
struct MultiplyIntInt: IntOp {
IntOp *pArg1, *pArg2;
MultiplyIntInt(IntOp *pArg1, IntOp *pArg2): pArg1(pArg1), pArg2(pArg2) { }
virtual int get() override { return pArg1->get() * pArg2->get(); }
};
int main()
{
ConstInt i3(3), i4(4);
MultiplyIntInt i3muli4(&i3, &i4);
std::cout << i3.get() << " * " << i4.get() << " = " << i3muli4.get() << '\n';
return 0;
}
Output:
3 * 4 = 12
Live Demo on coliru
As I mentioned std::function in post-answer conversation with OP, I fiddled a bit with this idea and got this:
#include <iostream>
#include <functional>
struct MultiplyIntInt {
std::function<int()> op1, op2;
MultiplyIntInt(std::function<int()> op1, std::function<int()> op2): op1(op1), op2(op2) { }
int get() { return op1() * op2(); }
};
int main()
{
auto const3 = []() -> int { return 3; };
auto const4 = []() -> int { return 4; };
auto rand100 = []() -> int { return rand() % 100; };
MultiplyIntInt i3muli4(const3, const4);
MultiplyIntInt i3muli4mulRnd(
[&]() -> int { return i3muli4.get(); }, rand100);
for (int i = 1; i <= 10; ++i) {
std::cout << i << ".: 3 * 4 * rand() = "
<< i3muli4mulRnd.get() << '\n';
}
return 0;
}
Output:
1.: 3 * 4 * rand() = 996
2.: 3 * 4 * rand() = 1032
3.: 3 * 4 * rand() = 924
4.: 3 * 4 * rand() = 180
5.: 3 * 4 * rand() = 1116
6.: 3 * 4 * rand() = 420
7.: 3 * 4 * rand() = 1032
8.: 3 * 4 * rand() = 1104
9.: 3 * 4 * rand() = 588
10.: 3 * 4 * rand() = 252
Live Demo on coliru
With std::function<>, class methods, free-standing functions, and even lambdas can be used in combination. So, there is no base class anymore needed for nodes. Actually, even nodes are not anymore needed (explicitly) (if a free-standing function or lambda is not counted as "node").
I must admit that graphical dataflow programming was subject of my final work in University (though this is a long time ago). I remembered that I distinguished
demand-driven execution vs.
data-driven execution.
Both examples above are demand-driven execution. (The result is requested and "pulls" the arguments.)
So, my last sample is dedicated to show a simplified data-driven execution (in principle):
#include <iostream>
#include <vector>
#include <functional>
struct ConstInt {
int n;
std::vector<std::function<void(int)>> out;
ConstInt(int n): n(n) { eval(); }
void link(std::function<void(int)> in)
{
out.push_back(in); eval();
}
void eval()
{
for (std::function<void(int)> &f : out) f(n);
}
};
struct MultiplyIntInt {
int n1, n2; bool received1, received2;
std::vector<std::function<void(int)>> out;
void set1(int n) { n1 = n; received1 = true; eval(); }
void set2(int n) { n2 = n; received2 = true; eval(); }
void link(std::function<void(int)> in)
{
out.push_back(in); eval();
}
void eval()
{
if (received1 && received2) {
int prod = n1 * n2;
for (std::function<void(int)> &f : out) f(prod);
}
}
};
struct Print {
const char *text;
explicit Print(const char *text): text(text) { }
void set(int n)
{
std::cout << text << n << '\n';
}
};
int main()
{
// setup data flow
Print print("Result: ");
MultiplyIntInt mul;
ConstInt const3(3), const4(4);
// link nodes
const3.link([&mul](int n) { mul.set1(n); });
const4.link([&mul](int n) { mul.set2(n); });
mul.link([&print](int n) { print.set(n); });
// done
return 0;
}
With the dataflow graph image (provided by koman900 – the OP) in mind, the out vectors represent outputs of nodes, where the methods set()/set1()/set2() represent inputs.
Output:
Result: 12
Live Demo on coliru
After connection of graph, the source nodes (const3 and const4) may push new results to their output which may or may not cause following operations to recompute.
For a graphical presentation, the operator classes should provide additionally some kind of infrastructure (e.g. to retrieve a name/type and the available inputs and outputs, and, may be, signals for notification about state changes).
Surely, it is possible to combine both approaches (data-driven and demand-driven execution). (A node in the middle may change its state and requests new input to push new output afterwards.)
You can use templates.
template <typename UnderlyingClass>
class MultiplyBy2
{
typedef int (UnderlyingClass::*func)();
func input_func;
UnderlyingClass *obj;
public:
MultiplyBy2(UnderlyingClass *object, func i) : obj(object), input_func(i) {}
int output()
{
return (obj->*input_func)() * 2;
}
};
int main()
{
// test
InputInt ii;
MultiplyBy2<InputInt> mii{ &ii, &InputInt::output };
RandomInt ri;
MultiplyBy2<RandomInt> mri{ &ri, &RandomInt::rand10 };
}
This is a bit convoluted. However I think you should be making an interface or class that returns a value and the objects should inherit from this. Then the operator class can take any class that inherits from the base/interface. Eg Make an BaseInt class that stores an int and has the output method/ RandomInt and InputInt should inherit from BaseInt

Creating multiple instances of c++ library

I am trying to create multiple instances of a static c++ library I wrote, but I can't create multiple instances of it... When I create two instances and write different data to them, I read the same data from both of the instances. Here is my code:
.cpp file:
// MathFuncsLib.cpp
// compile with: cl /c /EHsc MathFuncsLib.cpp
// post-build command: lib MathFuncsLib.obj
/*
DECLARING VECTORS
|3,6,4|
|9,1,5|
|2,0,2|
|5,3,6|
Should be inputted as:
int a[] = {3,6,4,9,1,5,2,0,2,5,3,6} with x = 3 and y = 4
Inputting training vals:
|0.1 (inp1),0.1 (inp2) ,0.1 (targeted output)| depends on the number of inputs and outputs
|9,1,5|
|2,0,2|
|5,3,6|
*/
//#include "stdafx.h"
#include "vector.h"
#include "iostream"
#define DEBUG
#include <stdexcept>
//using namespace std;
double* vectorLib::arrayPtr;
int vectorLib::x;
int vectorLib::y;
vectorLib::vectorLib(int xInp, int yInp) {
vectorLib::arrayPtr = new double[xInp*yInp];
vectorLib::x = xInp;
vectorLib::y = yInp;
//return 0;
}
double vectorLib::sigmoid(double inp) {
return 1 / (1 + exp(-inp));
}
double* vectorLib::getArrayPtr() {
return vectorLib::arrayPtr;
}
double vectorLib::read(int xInp, int yInp) {
#ifdef DEBUG
if (xInp >= vectorLib::x) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_READ\n";
while (1);
}
if (yInp >= vectorLib::y) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_READ\n";
while (1);
}
#endif // DEBUG
return *(arrayPtr + xInp + vectorLib::x*yInp);
}
void vectorLib::write(int xInp, int yInp, double data) {
#ifdef DEBUG
if (xInp >= vectorLib::x) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_WRITE\n";
while (1);
}
if (yInp >= vectorLib::y) {
std::cout << "X_OUT_OF_BOUNDS_VECTOR_WRITE\n";
while (1);
}
#endif // DEBUG
vectorLib::arrayPtr[xInp + vectorLib::x*yInp] = data;
}
void vectorLib::writeArr(double* inpArr) {
int i;
for (i = 0; i < vectorLib::x*vectorLib::y; i++) {
vectorLib::arrayPtr[i] = *(inpArr + i);
}
}
void vectorLib::sigmoidVect() {
int yy;
int xx;
for (yy = 0; yy < vectorLib::y; yy++) {
for (xx = 0; xx < vectorLib::x; xx++) {
write(xx, yy, sigmoid(read(xx, yy)));
}
}
write(0, vectorLib::y - 1, 1);
}
int vectorLib::getX() {
return vectorLib::x;
}
int vectorLib::getY() {
return vectorLib::y;
}
int vectorLib::totalVectSize() {
return vectorLib::x * vectorLib::y;
}
void vectorLib::printVector() {
int yy;
int xx;
for (yy = 0; yy < y; yy++) {
for (xx = 0; xx < x; xx++) {
std::cout << vectorLib::read(xx, yy);
if (xx + 1 != x) {
std::cout << ",";
}
}
std::cout << "\n";
}
}
vectorLib* vectorLib::vectorMult(vectorLib* vect1, vectorLib* vect2) {
#ifdef DEBUG
if (vect1->getX() != vect2->getY()) {
std::cout << "INPUTS_DONT_MATCH_VECTORMULT\n";
while (1);
}
#endif // DEBUG
vectorLib toRet(vect1->getX(), vect2->getY());
int i;
for (i = 0; i < vect2->getX(); i++) {
int p;
for (p = 0; p < vect1->getY(); p++) {
double tempOut = 0;
int q;
for (q = 0; q < vect1->getX(); q++)
{
tempOut += vect1->read(q, p) * vect2->read(i, q);
}
toRet.write(i, p, tempOut);
}
}
return &toRet;
}
.h file:
//#include "stdafx.h"
using namespace std;
class vectorLib
{
//int x, y;
public:
static double* arrayPtr;
static int x;
static int y;
//Constructor takes x and y of the vector
vectorLib(int xInp, int yInp);
//The pointer to the array that holds all the doubles in the vector
static double* getArrayPtr();
//Read the vector at a specified x and y
static double read(int xInp, int yInp);
//Write one double to a specific location
static void write(int xInp, int yInp, double data);
//Write the array inside the vector class
static void writeArr(double* inpArr);
//Takes sigmoid of whole vector
static void sigmoidVect();
//Returns x of vector
static int getX();
//Returns y of vector
static int getY();
//Returns total size of vector
static int totalVectSize();
//Returns a vector pointer to the multiplication result
static vectorLib* vectorMult(vectorLib* vect1, vectorLib* vect2);
//Prints vector
static void printVector();
private:
static double sigmoid(double inp);
};
Main file:
#define DEBUG
#include "stdafx.h"
#include "vector.h"
#include "iostream"
using namespace std;
int main()
{
vectorLib testVectLol(1, 3);
vectorLib testVect(3, 4);
double vectInp[] = { 1,1,1,
1,1,1,
1,1,1,
1,1,1};
double vectInp2[] = { 0.5,0.5,0.5 };
testVect.writeArr(vectInp);
testVectLol.writeArr(vectInp2);
testVect.printVector();// Both print 0.5, 0.5, 0,5
testVectLol.printVector();// Both print 0.5, 0.5, 0,5
while (1);
return 0;
}
Thanks in advance! I've been struggling with this for hours. I would really appreciate any help!
Jasper

"end must be large than start" in Uniform1dMesher

I try to build a pyd-file with QuantLib and Boost where I want to calculate the NPV for a barrier option. However the QuantLib pyd throws:
RuntimeError: end must be large than start
The error originates from the following Quantlib class in uniform1dmesher.hpp:
class Uniform1dMesher : public Fdm1dMesher {
public:
Uniform1dMesher(Real start, Real end, Size size)
: Fdm1dMesher(size) {
QL_REQUIRE(end > start, "end must be large than start");
const Real dx = (end-start)/(size-1);
for (Size i=0; i < size-1; ++i) {
locations_[i] = start + i*dx;
dplus_[i] = dminus_[i+1] = dx;
}
locations_.back() = end;
dplus_.back() = dminus_.front() = Null<Real>();
}
};
My c++-code is the following:
struct OptionInputs
{
QuantLib::Real S;
QuantLib::Real K;
QuantLib::Spread f;
QuantLib::Rate r;
QuantLib::Volatility vol;
QuantLib::Date maturity;
QuantLib::DayCounter dayCounter;
};
double FxOptEx(const OptionInputs &in,
const QuantLib::Date &todaysDate,
const QuantLib::Date &settlementDate)
{
using namespace QuantLib;
Calendar calendar = TARGET();
Settings::instance().evaluationDate() = todaysDate;
QuantLib::Real rebate = 0.05;
Size timeGird = 365;
Size underlyingGird = 100;
Size dampingSteps = 0;
Real theta = 0.05;
bool localVolatility = true;
boost::shared_ptr<Exercise> europeanExercise(
new EuropeanExercise(
in.maturity));
Handle<Quote>
underlyingH(boost::shared_ptr<Quote>(new SimpleQuote(in.S)));
Handle<YieldTermStructure>
rTS(boost::shared_ptr<YieldTermStructure>(new FlatForward(settlementDate,
in.r,
in.dayCounter)));
Handle<YieldTermStructure>
fTS(boost::shared_ptr<YieldTermStructure>(new FlatForward(settlementDate,
in.f,
in.dayCounter)));
Handle<BlackVolTermStructure>
flatVolTS(boost::shared_ptr<BlackVolTermStructure>(new BlackConstantVol(settlementDate,
calendar,
in.vol,
in.dayCounter)));
boost::shared_ptr<StrikedTypePayoff>
payoff(new PlainVanillaPayoff(Option::Put,
in.K));
boost::shared_ptr<BlackScholesMertonProcess> blackScholesMertonProcess(new BlackScholesMertonProcess(
underlyingH,
fTS,
rTS,
flatVolTS));
BarrierOption barrierOption(
QuantLib::Barrier::UpIn,
QuantLib::Option::Put,
rebate,
payoff,
europeanExercise);
barrierOption.setPricingEngine(
boost::shared_ptr<PricingEngine>(
new FdBlackScholesBarrierEngine (
blackScholesMertonProcess,
timeGird,
underlyingGird,
dampingSteps,
FdmSchemeDesc::ImplicitEuler(),
localVolatility,
-Null< Real >())));
return barrierOption.NPV();
}
struct FXOption
{
double value;
void set(int S, int K, double f, double r, double vol, std::string maturity, std::string dayCounter)
{
OptionInputs in;
in.S=S;
in.K=K;
in.f=f;
in.r=r;
in.vol=vol;
in.maturity=QuantLib::DateParser::parseISO(maturity);
if (dayCounter == "Actual365Fixed")
{
in.dayCounter = Actual365Fixed();
}
value = FxOptEx(in, Date(15, May, 1998), Date(17, May, 1998));
}
double get()
{
return value;
}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(quant)
{
class_<FXOption>("FXOption")
.def("get", &FXOption::get)
.def("set", &FXOption::set)
;
}
Any idea why this error is thrown?
Sorry I'm late to the party.
Difficult to say without seeing the actual invocation, but could it be that the maturity of the option is earlier than the settlement date?

having trouble with my ringupsale, showlast, and cancel function

This program uses inheritance and dynamic arrays
enum ItemType {BOOK, DVD, SOFTWARE, CREDIT};
class Sale
{
public:
Sale();
void MakeSale(ItemType x, double amt);
ItemType Item();
double Price();
double Tax();
double Total();
void Display();
private:
double price;
double tax;
double total;
ItemType item;
}
//****************************SALE.CPP*******************************
#include<iostream>
#include<cmath>
#include "sales.h"
using namespace std;
Sale::Sale()
{
price = 0;
tax = 0;
total = 0;
}
// Credit are suppose to have no tax all other purchases have
void Sale::MakeSale(ItemType x, double amt)
{
item = x;
if(item == CREDIT)
total = amt;
else
total = (amt * tax);
}
ItemType Sale::Item()
{
return item;
}
double Sale::Price()
{
return price;
}
double Sale::Tax()
{
return tax;
}
double Sale::Total()
{
return total;
}
// display function
void Sale::Display()
{
if(item = BOOK)
cout<<"BOOK"<<" "<<'$'<<price<<" ";
cout<<"Tax"<<" "<<'$'<<tax<<" "<<"Total:";
cout<<" "<<'$'<<total<<endl;
if(item = DVD)
cout<<"DVD"<<" "<<'$'<<price<<" ";
cout<<"Tax"<<" "<<'$'<<tax<<" "<<"Total:";
cout<<" "<<'$'<<total<<endl;
if(item = SOFTWARE)
cout<<"SOFTWARE"<<" "<<'$'<<price<<" ";
cout<<"Tax"<<" "<<'$'<<tax<<" "<<"Total:";
cout<<" "<<'$'<<total<<endl;
if(item = CREDIT)
cout<<"CREDIT" <<" "<<'$'<<price<<" ";
cout<<"Tax"<<" "<<'$'<<tax<<" "<<"Total:";
cout<<" "<<'$'<<total<<endl;
}
//****************************Register.h*******************************
#include<iostream>
#include "sales.h"
using namespace std;
const int BLOCKSIZE = 5;
class Register : Sales
{
public:
Register(int id, double start_amount);
~Register();
int GetID();
double GetAmount();
void RingUpSale(enum ItemType Saletype, double amount);
void ShowLast();
void ShowAll();
void Cancel();
double SalesTax(int n);
private:
int Register_ID;
int Current_ArraySize;
int Number_of_Records;
double Register_Amount
Sale *Sales_Array;
Sale *Temp_Array;
void expandlist();
void shrinklist();
}
//******************************Register.cpp*********************************
#include<iostream>
#include "register.h"
using namespace std;
// *******************************************************************
// * Initializing these values for a starting value
// *******************************************************************
int Current_ArraySize = 0;
int Number_of_Records = 0;
// ******************************************************************
// *
// * Function: Constructor for Register
// * Parameters: ID number and starting amount
// *
// * Description: Initializes the ID number and the register amount
// *
// ******************************************************************
Register::Register(int id, double amount)
{
int * Sales_Array;
Sales_Array = new int[BLOCKSIZE];
int Register_ID = id;
double Register_amount = amount;
}
// ******************************************************************
// *
// * Function: Destructor for Register
// * Parameters:
// *
// * Description: Deletes Sales Array
// *
// ******************************************************************
Register::~Register()
{
delete[] Sales_Array;
}
// ******************************************************************
// *
// * Function: GetID
// * Parameters:
// *
// * Description: returns ID
// *
// ******************************************************************
int Register::GetID()
{
return Register_ID;
}
// ******************************************************************
// *
// * Function: GetAmount
// * Parameters:
// *
// * Description: returns amount
// *
// ******************************************************************
double Register::GetAmount()
{
return Register_Amount;
}
// ******************************************************************
// *
// * Function: RingUpSale
// * Parameters: enum ItemType amd amount
// *
// * Description: Takes in items sold and amount then adds them
// * to the previous list.
// *
// ******************************************************************
Not sure why ringupsale is not working!
void Register::RingUpSale(enum ItemType Saletype, double amount)
{
Current_ArraySize++;
newSale_Array = new Sales_Array[Current_ArraySize];
//copy all the old sale items into the new list.
for (int i=0; i<Current_ArraySize; i++)
{
newSale_Array[i] = Sales_Array[i];
}
//add the new sale at the end of the new array
newSale_Array[Current_ArraySize-1] = newSale;
//set the sale array as the new array
Sales_Array = newSale_Array;
Number_of_Records++;
}
// ******************************************************************
// *
// * Function: ShowAll
// * Parameters:
// *
// * Description: Lists the contents of the register
// *
// ******************************************************************
I am trying to show all the contents of the sales array
void Register::ShowAll()
{
int i;
cout << "the elements int the array are:" <<endl;
// for(i=0; i<Current_ArraySize; i++)
// cout << Sales_Array(Sales_Array+i) << endl;
}
// ******************************************************************
// *
// * Function: ShowLast
// * Parameters:
// *
// * Description: Show the last transaction made
// *
// ******************************************************************
I am just trying to show the last content of the sales array
void Register::ShowLast()
{
cout << "The last sale was:" << endl;
// cout << Sale[Current_ArraySize - 1] << endl;
}
// ******************************************************************
// *
// * Function: Salestax
// * Parameters:
// *
// * Description: returns the amount of salestax
// *
// ******************************************************************
double Register::SalesTax(int n)
{
double RunTotal=0;
if (n<0)
{
cout<<"Invalid entry.";
return 0;
}
else if (n>Number_of_Records)
{
for(int i=0; i<=Number_of_Records; i++)
{
RunTotal=RunTotal+Sales_Array[i].Tax();
return RunTotal;
}
}
else
{
for(int i=0; i<=n; i++)
{
RunTotal=RunTotal+Sales_Array[i].Tax();
return RunTotal;
}
}
}
This is a problem:
Register::Register(int id, double amount)
{
int * Sales_Array;
Sales_Array = new int[BLOCKSIZE];
int Register_ID = id;
double Register_amount = amount;
}
as the local variable Sales_Array in the constructor of Register hides the member variable Register::Sales_Array, meaning Register::Sales_Array is an unintialised pointer. Register::Sales_Array is then used, causing undefined behaviour and will be the reason that Register::RingUpSale() is not working. Remove the declarations in the constructor and use an initializer list instead:
Register::Register(int id, double amount) :
Current_ArraySize(0),
Number_of_Records(0),
Sales_Array(0),
Register_ID(id),
Register_Amount(amount)
{}
Note that these lines introduced two new variables, unrelated to the class:
int Current_ArraySize = 0;
int Number_of_Records = 0;
Have also added these to the initializer list above.
Finally, you are violating the Rule of Three as you have dynamically allocated members but have not defined a copy constructor and assignment operator, or at least declared them private to make Register uncopyable.
As this is C++, use a std::vector<Sale> instead of explicitly managing dynamic memory.