I have a class that contains a variable 'beta'. I want to run the code with 1000 different values of 'beta' that range between 0 and 1. My first thought was to run a loop but I am unable to do this within a class. I also have tried using pointers but this did not seem to work. I apologise if my question is rather amateur but I am a Math grad, not computer science. Can someone please help!
The code for my class is listed below.
class FalknerSkan : public MFunction
{
public:
//constuctor to initialise kappa
FalknerSkan() {beta = 0.0;}
MVector operator()(const double& x, const MVector& y)
{//y[0]=f, y[1]=f', y[2]=f'', y[3]=Z1, y[4]=Z2, y[5]=Z3
MVector temp(6);
temp[0] = y[1];
temp[1] = y[2];
temp[2] = -y[0]*y[2] - beta*(1-y[1]*y[1]);
temp[3] = y[4];
temp[4] = y[5];
temp[5] = -y[2]*y[3] + 2.0*beta*y[1]*y[4] - y[0]*y[5];
return temp;
}
void SetKappa(double k) {beta = k;} //change kappa
private:
double beta; // class member variable, accessible within
//all FalknerSkan member functions
};
Thank you
This is a loop inside a class.
#include <iostream>
class Foo
{
public:
Foo() : beta(0.0)
{}
void print(){
for (int i(0); i < 1000; ++i)
std::cout << ++beta << std::endl;
}
private:
double beta;
};
int main()
{
Foo obj;
obj.print();
return 0;
}
Related
Following my question, I coded a simple tool to compute a root using the bisection method, which is working fine. Here is the code:
roots.h
#ifndef ROOTS_H
#define ROOTS_H
class FunctRoots {
public:
// default constructor
FunctRoots();
// destructor
virtual ~FunctRoots();
// return the error
virtual double evaluate(double x);
};
class Roots{
private:
double tol=1e-5;
int max_iter=100;
double a, b;
double fa=0.0;
double fb=0.0;
public:
// default constructor
Roots();
// destructor
virtual ~Roots();
// set tolerance
void set_tolerance(double tolerance);
// set the search space
void set_search_space(double a, double b);
// bracketing
void bracketing(FunctRoots& problem, double start, double step);
// bisection method
double bisection(FunctRoots& problem);
};
#endif
roots.cpp
#include "roots.h"
#include "iostream"
#include "cmath"
// define the template for the function
FunctRoots::FunctRoots () {}
FunctRoots::~FunctRoots () {}
double FunctRoots::evaluate(double x){
return 0.0;
};
// Roots class
Roots::Roots() {}
Roots::~Roots() {}
// set search space
void Roots::set_search_space(double a, double b){
this->a = a;
this->b = b;
}
// set tolerance
void Roots::set_tolerance(double tolerance){
this->tol = tolerance;
}
// bracketing
void Roots::bracketing(FunctRoots& problem, double start, double step){
// set initial boundary
this->a = start;
this->fa = problem.evaluate(this->a);
// main loop
this->b = start;
for (int iter = 0; iter < max_iter; iter++) {
// update upper boundary
this->b += step;
this->fb = problem.evaluate(this->b);
// check if a root exists
if (this->fa*this->fb < 0) break;
// update lower bound
this->a = this->b;
this->fa = this->fb;
}
// check boundaries
if (this->a > this->b){
double temp;
temp = this->a;
this->a = this->b;
this->b = temp;
temp = this->fa;
this->fa = this->fb;
this->fb = temp;
}
}
// bisection method
double Roots::bisection(FunctRoots& problem){
// variables declaration
double fx, x;
// compute errors
if (fabs(this->fa) < 1e-12){
this->fa = problem.evaluate(this->a);
}
// main loop
x = 0;
for (int iter = 0; iter < max_iter; iter++) {
// compute solution
x = (a+b)/2.0;
fx = problem.evaluate(x);
// print on screen
std::cout << "iter=" << iter << "\n";
std::cout << "a=" << a << "\n";
std::cout << "b=" << b << "\n";
std::cout << "x=" << x << "\n";
std::cout << "fx=" << fx << "\n\n";
// stop criterion
if (fabs(fx) < this->tol) break;
// update boundaries
if (this->fa*fx < 0){
this->b = x;
}else{
this->a = x;
this->fa = fx;
}
}
// function return
return x;
}
main.cpp
#include "roots.h"
#include "cmath"
class Problem: public FunctRoots{
private:
double value;
public:
Problem(double value){
this->value = value;
}
double evaluate(double x) {
return pow(cos(x),2)+this->value-x;
}
};
int main(){
Problem problem(6);
Roots roots;
//roots.set_search_space(5, 10);
roots.set_tolerance(1e-7);
roots.bracketing(problem, 0,0.1);
roots.bisection(problem);
return 0;
}
Now, the question is this: how can I make my main looks like this?
int main(){
Problem problem(6);
Roots roots;
roots.set_problem(problem) // <----NEW
//roots.set_search_space(5, 10);
roots.set_tolerance(1e-7);
roots.bracketing(0,0.1); // <---- problem is not here anymore
roots.bisection(); // <---- problem is not here anymore
return 0;
}
Basically, I would like to define my problem once and for all just after initializing the solver so that I don't need to give it as input to the functions anymore, however considering that the function evaluate is defined in FunctRoots but then overridden in Problem.
I would like to define my problem once and for all just after initializing the solver …
You can add a reference to a FunctRoots object as a member of your Roots class:
class Roots {
private:
FunctRoots& problem;
double tol = 1e-5;
//...
However, rather than initializing this "just after initializing the solver", you would need to intialize it at the time of creating that solver (i.e., pass it as a parameter to the constructor and initialize the member variable in an initializer list). So, your Roots constructor would then look like this:
Roots::Roots(FunctRoots& fr) : problem{ fr } {}
You can then (as you desire) remove the reference to the Problem object in your bracketing and bisection methods, and your main would look like:
int main() {
Problem problem(6);
Roots roots(problem); // Initializes reference member at construction
roots.set_tolerance(1e-7);
roots.bracketing(0, 0.1); // <---- problem is not here anymore
roots.bisection(); // <---- problem is not here anymore
return 0;
}
Note that such reference members must be initialized at object construction time; they cannot then be reassigned to refer to different objects. Also note that polymorphism works with references, just as it does with pointers.
How to define a class member with a reference
It's as simple as that, just declare a member reference and create a constructor to initialize it:
class Member{};
class MyClass{
Member& member;
public:
MyClass(Member& m) : member(m) {}
};
int main(){
Member m;
MyClass cl(m);
}
Note that the lifetime of Member must be at least the same as MyClass otherwise you will end up with a dangling referece.
In this case, I think your root class should either
have member variable "problem", and initialize it when you call roots.set_problem(problem).
like
class Roots {
private:
Problem *myProblem;
public:
void set_problem(Problem &problem){
myProblem = new Problem(problem.value)
}
}
or have other variable members that could store value you give with roots.set_problem(problem).
I keep getting this error that only virtual functions can be marked as override but the functions in question "norm()" and "string to_string()" are virtual. what could be causing this?
In my main function I am also getting the error no matching member function to call push back, did I make a mistake along the way somewhere and I am just not seeing it?
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
class Group
{
public:
virtual string to_string() = 0;
virtual int norm() = 0;
};
class Real
{
// add your code here
protected:
int number;
public:
Real(int num)
{
number = num;
}
int norm() override
{
return number;
}
string to_string() override
{
return number;
}
int getNumber() const
{
return number;
}
void setNumber(int number)
{
Real::number = number;
}
};
class Complex : public Real
{
// add your code here
protected:
int imaginary;
public:
Complex(int realNum, int imag) : Real(realNum)
{}
int norm() override
{
return sqrt(number * number + imaginary * imaginary) + 'i';
}
string to_string() override
{
return ::to_string(number) + '+' + ::to_string(imaginary) + 'i';
}
};
class Trinomial : public Complex
{
// add your code here
protected:
int third;
public:
Trinomial(int p1, int p2, int p3) : Complex(p1, p2) {
third = p3;
}
int norm() override {
return sqrt(number * number + imaginary * imaginary + third * third);
}
string to_string() override {
return ::to_string(number) + "x^2+" + ::to_string(imaginary) + "x+" + ::to_string(third);
}
};
class Vector : public Group
{
// add your code here
protected:
vector<int> v;
public:
Vector(int num1, int num2, int num3)
{
v.push_back(num1);
v.push_back(num2);
v.push_back(num3);
}
int norm() override
{
int squared_sum = 0;
for (int i = 0; i < v.size(); i++) {
squared_sum += v[i] * v[i];
}
return sqrt(squared_sum);
}
string to_string() override
{
string str = "[";
for (int i = 0; i < v.size() - 1; i++) {
str += ::to_string(v[i]) + " ";
}
str += ::to_string(v[v.size() - 1]) + "]";
return str;
}
};
int main()
{
vector<Group*> elements;
elements.push_back(new Real{ 3 });
elements.push_back(new Complex{ 3,4 });
elements.push_back(new Trinomial{ 1,2,3 });
elements.push_back(new Vector{ 1,2,3 });
for (auto e : elements)
{
cout << "|" << e->to_string() << "| = " << e->norm() << endl;
}
for (auto e : elements)
delete e;
return 0;
}
A couple of issues here:
The class Real must have inherited from Group so that you could override the functions. That is the reason for the error message.
Secondly the Real::to_string must return a string at the end. You
might convert the integer using std::to_string.
Last but not least the Group must have a virtual destructor for defined behaviour. Read more here: When to use virtual destructors?
In short, you need
#include <string>
class Group
{
public:
// other code
virtual ~Group() = default;
};
class Real: public Group // --> inherited from base
{
// other codes
public:
std::string to_string() override {
return std::to_string(number);
}
};
As a side, please do not practice with using namespace std;
your class real has no parent. so you cant override to_string()
I Have this sandbox code for a proyect more complicated :
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
class Table
{
friend class Variable;
public:
Variable * variables[1021];
};
class Variable
{
friend class Nodo;
public:
char clas;
Nodo * ini;
};
class Nodo
{
public:
char clas;
Variable * father;
private:
float * value;
public:
Nodo();
void set_value(float);
float * get_value();
};
Nodo::Nodo()
{
clas = ' ';
father = NULL;
value = NULL;
}
void Nodo::set_value(float m)
{
float * r = new float();
r = &m;
value = (float *)r;
}
float * Nodo::get_value()
{
return this->value;
}
And this is the main:
void main ()
{
Nodo * n = new Nodo(); // OK.
n->set_value(5.3442); // Ok.
Variable * v = new Variable(); // This is the problem.
// When I declare another pointer an initilized it, n lost the value stored in value.
Variable * v0 = new Variable(); // Here the same.
v->ini = n;
n->father = v;
Table * t = new Table();
t->variables[0] = v;
v0 = t->variables[0];
cout << *(static_cast<float *>(v0->ini->get_value())) << endl;
}
How can I stock the value in the pointer without change? It seems that I should use const, or something similar, but I don't know how. Declaring the field value as private doesn't help. The idea is replace value with a void * later, to store any king of basic date not only float data.
Thanks!
This looks wrong:
void Nodo::set_value(float m)
{
float * r = new float();
r = &m;
value = (float *)r;
}
r is assigned pointer to m which is a temporary, this pointer will be invalid once set_value finishes. Also you overwrite r value, so you have a leak here. The correct version would be:
void Nodo::set_value(float m)
{
float * r = new float();
*r = m;
value = r;
}
btw. I am not digging deeper in your code, ...
I implemented a googletest, with fixture class UnitTest_solver. Implementation for the fixture is the following. It contains helper functions
class UnitTest_solver : public ::testing::Test
{
protected:
static void SetUpTestCase()
{
// setup table with data
m_col = 2;
m_row = 100;
// other things to initialize m_test_data
}
static void TearDownTestCase()
{
for(int i = 0 ; i < m_row ; i++)
delete[] m_test_data[i];
delete[] m_test_data;
}
static double chi_sqr(double* x)
{
if(m_col < 2)
return 0;
double fx = 0;
double * row_i = new double[m_col - 1];
for(int i = 0 ; i < m_row ; i++)
{
for(int j = 0 ; j < m_col - 1 ; j++)
row_i[j] = m_test_data[i][j];
fx += pow(m_test_data[i][0] - func_1(x, row_i, m_col - 1), 2.0);
}
return fx;
}
static double func_1(double* x, double* dbl, int nb_param)
{
if(nb_param != 2)
return 0;
return x[0] * exp(-1 * x[1] * dbl[0]);
}
static double UnitTest_solver::functPtr( double * parameters, void * userinfo)
{
return chi_sqr(parameters);
}
static ofstream thing;
static double** m_test_data;
static int m_col, m_row;
};
Also, out of the fixture scope, i initialize static variables. Last is function pointer. is definition syntax ok ?
double** UnitTest_solver::m_test_data = 0;
int UnitTest_solver::m_col = 0;
int UnitTest_solver::m_row = 0;
double (UnitTest_solver::*functPtr)(double * , void *) = 0;
then, i have a test case, with link to fixture UnitTest_solver.
TEST_F(UnitTest_solver, testFunc1)
{
Solver* solversqp = new Solver();
solversqp->set_pointer_to_function(UnitTest_solver::functPtr, (void*)0);
//...
}
second line show compile time error with UnitTest_solver::functPtr : when mouse is over the error, info is 'function defined at line xxx is unacessible', with xxx pointing to functPtr definition inside the fixture.
If i run the ggltest commenting the last line, solversqp->set_pointer_to_function(UnitTest_solver::functPtr, (void*)0);, test is finishing (if i put a trivial ASSERT, it is successful).
Whats wrong with my function pointer definition.
I do not see full code, therefore this is just a guess.
Everything in class UnitTest_solver is protected, therefore everything (other then classes inheriting for this class) do not have access to it's members. Change it to public, and your problem will be solved :
class UnitTest_solver : public ::testing::Test
{
// protected:
public:
In C++ I have an array of doubles which need initialising programmatically, at run time, just once, for the whole class to share. They could be both static and constant. How best can I initialise them? I have gone off using static with the prodigious popularity of parrallel processors presently pervading. So must I set a flag to run once or is there some static const magic which will initialise them as a variable local to a function (ok) or class (ok too)?
double sumOfWeights = 0.0;
double fracObs = 0.0;
for (int i = 0; i < NUMTRACES; i++) {
double weightAtI = SQUARED(1 - SQUARED(MAXTRACEWRTMIDTRACE * (MIDTRACE - i)
/ double(MIDTRACE)));
sumOfWeights += weightAtI;
fracObs += obsArray[i] * weightAtI;
}
return fracObs / sumOfWeights;
In the code above I'd like to make weightAtI a lookup with each double already divided by sumOfWeights so I can retrieve them without iterating through NUMTRACES.
_EDIT_
It's okay, that's what constructors are for :)
Just hoping to tackle my static, const and initialization gremlins into the bargain. Thanks Seth
_EDIT_
Not sure it is quite the effect I wanted though. The constructor runs on each instance, even if the members are static, no? No. Lemme see...
_EDIT_
I think the most efficient solution, is to guard the initializer loop with a static flag, in the constructor. Being a POD flag I'm sure it should behave appropriately, I'm just not quite sure what that is at this stage.
_EDIT_
Ahh, got it:
class X
{
public:
static int i;
};
int X::i = 0; // definition outside class declaration
_EDIT_
Unfortunately, when it comes to my code,
static const int MIDTRACE = 3;
static const int NUMTRACES = 2 * MIDTRACE + 1;
static double WEIGHTATI[NUMTRACES];
I get linker errors:
meobj.obj : error LNK2020: unresolved token (0A00001C) "private: static double * mens:meclass::PIMPL::WEIGHTATI" (?WEIGHTATI#PIMPL#meclass#mens##$$Q0PANA)
meobj.obj : error LNK2001: unresolved external symbol "private: static double * mens:meclass::PIMPL::WEIGHTATI" (?WEIGHTATI#PIMPL#meclass#mens##$$Q0PANA)
due to my constructor:
meclass::PIMPL() {
if (!doneStaticInit) {
double sumOfWeights = 0.0;
for (int i = 0; i < NUMTRACES; i++) {
WEIGHTATI[i] = SQUARED(1 - SQUARED(MAXTRACEWRTMIDTRACE * (MIDTRACE - i) / double(MIDTRACE)));
sumOfWeights += WEIGHTATI[i];
}
for (int i = 0; i < NUMTRACES; i++) WEIGHTATI[i] /= sumOfWeights;
doneStaticInit = true;
}
}
Initialization => constructor. Once => static instance. So one way is static instance of something with constructor.
#include <iostream>
struct Foo
{
Foo()
{
std::cout << "Initializing them values..." << std::endl;
for( int i = 0; i < 3; ++i )
{
values[i] = i;
}
};
int values[3];
};
void doThings()
{
static Foo const foo; // Is initialized ONCE.
for( int i = 0; i < 3; ++i )
{
std::cout << foo.values[i] << " ";
}
std::cout << std::endl;
}
int main()
{
doThings();
doThings();
doThings();
}
Cheers & hth.,
You can put a static bool flag in your constructor. The flag will only be initialized to false the first time it is called. After that it will remain true.
// foo.h
class Foo {
static const int MIDTRACE = 3; // static const, no definition needed
static const int NUMTRACES = 2 * MIDTRACE + 1; // static const, no definition needed
static double WEIGHTATI[NUMTRACES]; // not const, so need definition outside of class
public:
Foo() {
static bool array_initialized = false;
if( !array_initialized ) {
// Initialize array
array_initialized = true;
}
}
// Other members
};
In a source file, not header file:
// foo.cpp
include "foo.h"
double Foo::WEIGHTATI[NUMTRACES];