Variables printing as nan or inf instead of actual value - c++

I'm working on a program that calculates time based off of distance and speed and when I out put the final time it would take to get from point a to point b instead of getting 100 miles I'm getting either nan or inf depending on how my class is set up. Can someone help me out here?
Part of my class:
class Trip
{
private:
string chicago, illinois, destCity, destState;
double distance, time, rate;
public:
Trip()
{
chicago = "Chicago";
illinois = "Illinois";
destCity = "";
destState = "";
distance = 0.0;
time = 0.0;
rate = 0.0;
}
Trip(string city, string state, double distance)
{
chicago = "Chicago";
illinois = "Illinois";
destCity = city;
destState = state;
distance = 0.0;
time = 0.0;
rate = 0.0;
}
This is what a constructor would look like in my main method:
Trip atlanta("Atlanta", "Georgia", 587);
and then here are some mutator methods that could be part of the problem:
void Trip::setRate(double mph)
{
mph = rate;
}
void Trip::calcTime()
{
time = distance/rate;
}
now if i set up my class like so
this->city = "";
this->distance = 0.0;
when I use an accesor method to retrieve time, distance, etc is prints as "nan" but if I have my class set up like it
city = "";
distance = 0.0;
then I get "inf".
When I debug the program the trip object shows up with all the variables being 0 even after I pass values to the class members with the constructor. I don't know what's going wrong.

In this function:
Trip(string city, string state, double distance)
{
// ...
distance = 0.0;
that last line sets the function parameter distance. Not the class member. The class member remains uninitalized , so you get garbage when you print it out sometimes.
To fix this you could write this->distance = 0.0;, or preferably use constructor initialization lists:
Trip(string city, string state, double distance)
: chicago("Chicago")
, distance(distance)
, // etc.
{
}
And/or use different names for the parameters than you use for the class members.
In the initialization list, distance(distance) means that this->distance is initialized to the parameter distance, because the thing outside the parentheses has to be the name of a class member.
In C++11 you can set default values in the class definition, which avoids you having to repeat them in every constructor:
class Trip
{
private:
string chicago, illinois, destCity, destState;
double distance = 0.0;
double time = 0.0;
double rate = 0.0;
Note that there is no need to initialize strings to blank; they have a default constructor, so uninitialized strings are guaranteed to be empty strings, not garbage.

Related

Matlab class multiple accessors for same data

I'm trying to translate a class from C++ to Matlab. In C++, the same data can be accessed in multiple ways because the values are declared as a union.
However, it seems like the only way to do this in Matlab is to override subsref and subsasgn, which opens up a can of worms of having to parse methods.
Is there a different way to handle this? I saw some comments from 2014 indicating there wasn't
This is the C++ enum in question:
template <class T>
class Euler
{
public:
union
{
T m[3];
struct
{
union { T x; T yaw; T psi; }; // m[0]
union { T y; T pitch; T theta; }; // m[1]
union { T z; T roll; T phi; }; // m[2]
};
};
};
The simple solution: forget about these names, and translate this class as a simple array, indexing m.x as m[1], m.roll as m[2], etc. This might not be great for some use cases, but certainly is the most efficient solution.
The alternative solution requires creating a custom class. subsref and subsasgn are not necessary, it is possible to declare dependent properties and define getters and setters (though it's not pretty!):
classdef Euler
properties
x = 0;
y = 0;
z = 0;
end
properties (Dependent)
yaw, pitch, roll;
psi, theta, phi;
end
methods
function value = get.yaw(obj)
value = obj.x;
end
function value = get.pitch(obj)
value = obj.y;
end
function value = get.roll(obj)
value = obj.z;
end
function obj = set.yaw(obj,value)
obj.x = value;
end
function obj = set.pitch(obj,value)
obj.y = value;
end
function obj = set.roll(obj,value)
obj.z = value;
end
% Add same methods for psi, theta, phi.
end
end
You can now do:
e = Euler;
e.x = 1;
e.yaw % returns 1
e.roll = 5;
e.z % returns 5
That is, the object has properties x, y, z, yaw, pitch and roll (and after adding appropriate setters and getters also psi, theta and phi), but only stores three values. The values of e.g. yaw and x are linked, and always identical.

What does gen~ phasor() do? (Translating Max/MSP gen to C++)

We have two places in the same gen~ code box object with phasor:
wander = phasor(in8/dense);
...some code later...
phas = (triangle(phasor(freq), sharp)*len-rot_x/(2*pi))%1;
I understand that phasor() produces a rising sawtooth, outputting values of 0 to 1. I understand the argument of phasor() is frequency. What I don't understand is how phasor() can output a value of 0 to 1 given frequency, when you would need frequency over time to produce a value other than 0. It would seem that phasor(frequency) should always output 0 unless somehow phasor() is keeping track of time and its own phase.
If phasor is keeping track of time/phase, how can we call phasor() twice in the same gen code box? It would seem impossible that we could have two time values. Unless...
...we have one time/phase value shared between all calls to phasor() but it is the last call to phasor() that sets the final frequency before phasor() increments its phase, which happens at the end of the code block.
Am I correct?
Edit: No that can't be, then why would you ever put a frequency into phasor twice? It wouldn't change the output under my logic.
From my tests, phasor is indeed a sawtooth oscillator object where each call to phasor is a unique oscillator, so, calling phasor twice in the same code box will instantiate two objects.
class Phasor
{
public:
double getSample()
{
double ret = phase/PI_z_2;
phase = fmod(phase+phase_inc, TAU); //increment phase
return ret;
}
void setSampleRate(double v) { sampleRate = v; calculateIncrement(); }
void setFrequency(double v) { frequency = v; calculateIncrement(); }
void reset() { phase = 0.0; }
protected:
void calculateIncrement() { phase_inc = TAU * frequency / sampleRate; }
double sampleRate = 44100.0;
double frequency = 1.0;
double phase = 0.0;
double phase_inc = 0.0;
const double TAU = 2*PI;
const double PI_z_2 = PI/2.0;
};

C++ Vector - Emplace/Erase not working?(Polymorphism)

I'm having some problems with polymorphism I have a superclass of CEntity, and a subclass of unit type, I am dynamic casting and removing and emplacing a new entity of the dynamic casts type at its place, I have the opposite problem of my previous question.
Problem is the values being set are not changing, it remains with default values, it appeared to work before but now it has stopped working, I'm not sure what has caused the issue.
specifically buildsetup, sets the x-y-z values of the unit subclass's x,y,z, but when I look inside the vector the values remain unchanged, this is strange because it does actually manage to change the values for whether the unit is alive or not.
void builder(int no, string in , int top, int bot, CTeam &team, string owner, string original)
{
for (int i = top; i <= bot; i++)
{
EntityUnit* a;
a = dynamic_cast<EntityUnit*>(AWorld.EntitiesVector[i]);
a->unit_alive;
if (a->unit_alive == false)
{
float x = Player.returncity_add().cit_ret_X();
float y = Player.returncity_add().cit_ret_Y();
float z = Player.returncity_add().cit_ret_Z();
cout << "X:" << x;
cout << "Y:" << y;
cout << "Z:" << z;
float cost = MainAB.UnitTemplates[no]->UDRetCost();
float health = MainAB.UnitTemplates[no]->UDRetMaxHealth();
float damage = MainAB.UnitTemplates[no]->UDRetStrength();
float speed = MainAB.UnitTemplates[no]->UDRetSpeed();
float buildtime = MainAB.UnitTemplates[no]->UDRetBuildTime();
int popcost = MainAB.UnitTemplates[no]->UDRetPop();
a->set_owner(owner);
setmodel(i, x, y, z); // takes an xyz by ref and sets the model
to them then changes the model's localz by -10
Units[i]->SetSkin(setskin(owner, original));
a->BuildSetup(x, y, z, health, damage, speed, buildtime, cost, popcost);
team.inc_popcount(a->UDRetPop());
a->set_unit_alive(true);
sBuildUnit.play();
AWorld.EntitiesVector.erase(AWorld.EntitiesVector.begin() + i);
AWorld.EntitiesVector.emplace(AWorld.EntitiesVector.begin() + i, new EntityUnit(a));
AWorld.EntitiesVector[i]->set_x(x);
AWorld.EntitiesVector[i]->set_y(y);
AWorld.EntitiesVector[i]->set_z(z);
break;
}
}
Entity build setup
void EntityUnit::BuildSetup(float x, float y, float z,float _health, float _damage, float _speed, float _buildtime, float _cost, int _popcost)
{
unit_x = x;
unit_y = y;
unit_z = z;
unit_health[0] = _health;
unit_health[1] = _health;
unit_damage = _damage;
speed = _speed;
buildtime = _buildtime;
cost = _cost;
CUnitType = NA;
pop_req = _popcost;
}
After static debugging it, it most definately emplaces a new unit with the updated -is_alive, and while a's values change at the point of unitbuild, when its emplaced all x,y,z's return to 9999, which was what it was when they were pushed on the vector.
When you call
AWorld.EntitiesVector.erase(AWorld.EntitiesVector.begin() + i);
you destroy the object pointed to by a. The subsequent reference to it on the next line is Undefined Behavior, and anything is possible.
I'm not sure why you erase the entity, then try to put a new one in the same place. If you structure your code right you should be able to just reuse the existing entity (pointed to by a) without the erase and emplace calls.
Ok, Apparently the problem was it was totally unnecessary to erase/emplace, as I get what you mean now returning a pointer, it edited the value... odd it didn't work last time.

How to separate 2 values returned by a function into 2 different variables C++

The function that return the values is this
float calcVelocity(float xacceleration, float yacceleration,sf::Clock clock, float originalDistance){
sf::Time time = clock.getElapsedTime(); //get current time and store in variable called time
float xvelocity = xacceleration*time.asSeconds();
float yvelocity = yacceleration*time.asSeconds();
while (!(originalDistance + calcDisplacement(yacceleration, clock, originalDistance) <= 0)) {
time = clock.getElapsedTime(); //get current time and store in variable called time
xvelocity = xacceleration*time.asSeconds();//Calculates velocity from acceleration and time
yvelocity = yacceleration*time.asSeconds();
cout << xvelocity<<endl;//print velocity
cout << yvelocity << endl;
system("cls");//clear console
}
return xvelocity;
return yvelocity;
}
I then want them to print as finalXvelocity = blah and finalYvelocity = blah after the while loop is finised. In the main code when I call the function and output the result, it prints both values together. E.g finalXvelocity = blahblah.
I was thinking I could separate the values returned into the main code and then print them using those but I don't know how to do that.
Thanks
Use a struct:
struct velocity
{
float x_component; /*ToDo - do you really need a float*/
float y_component;
};
This will be the most extensible option. You can extend to provide a constructor and other niceties such as computing the speed. Perhaps a class is more natural, where the data members are private by default.
If you have more than one return value, since C++11 you can return them as a std::tuple. No need to explicit declare a data struct.
e.g.
tuple<float,float> calcVelocity(/*parameters*/) {
// your code
return make_tuple(xvelocity,yvelocity);
}
Outside the function you can access the values by:
tuple mytuple = calcVelocity(/*parameters*/);
float xvelocity = get<0>(my_tuple);
float yvelocity = get<1>(my_tuple);
For pre-C++11 std::pair is also an option for just 2 values. But in this case the struct solution is more explicit.

How to measure the rate of rise of a variable

I am reading in a temperature value every 1 second/minute (this rate is not crucial). I want to measure this temperature so that if it begins to rise rapidly above a certain threshold I perform an action.
If the temperature rises above 30 degrees ( at any rate ) I increase the fan speed.
I think I must do something like set old temperature to new temp and then each time it loops set old temp to the current temp of the engine. But I am not sure if I need to use arrays for the engine temp or not.
Of course you can store just one old sample, then check difference like in:
bool isHot(int sample) {
static int oldSample = sample;
return ((sample > 30) || (sample - oldSample > threshold));
}
It's OK from C point of view, but very bad from metrology point of view. You should consider some conditioning of your signal (in this case temperature) to smothen out any spikes.
Of course you can add signal conditioning letter on. For (easy) example look at Simple Moving Avarage: https://en.wikipedia.org/wiki/Moving_average
If you want control the fan speed "right way" you should consider learning a bit about PID controller: https://en.wikipedia.org/wiki/PID_controller
Simple discrete PID:
PidController.h:
class PidController
{
public:
PidController();
double sim(double y);
void UpdateParams(double kp, double ki, double kd);
void setSP(double setPoint) { m_setPoint = setPoint; } //set current value of r(t)
private:
double m_setPoint; //current value of r(t)
double m_kp;
double m_ki;
double m_kd;
double m_outPrev;
double m_errPrev[2];
};
PidController.cpp
#include "PidController.h"
PidController::PidController():ControllerObject()
{
m_errPrev[0] = 0;
m_errPrev[1] = 0;
m_outPrev = 0;
}
void PidController::UpdateParams(double kp, double ki, double kd)
{
m_kp = kp;
m_ki = ki;
m_kd = kd;
}
//calculates PID output
//y - sample of y(t)
//returns sample of u(t)
double PidController::sim(double y)
{
double out; //u(t) sample
double e = m_setPoint - y; //error
out = m_outPrev + m_kp * (e - m_errPrev[0] + m_kd * (e - 2 * m_errPrev[0] + m_errPrev[1]) + m_ki * e);
m_outPrev = out; //store previous output
//store previous errors
m_errPrev[1] = m_errPrev[0];
m_errPrev[0] = e;
return out;
}