I have the following problem where I will get an access violation exception when trying to print a variable, but only after a loop has run a specific number of times.
Specifically on the 211th iteration, the line:
cout << "Frame " << i << ", Recall: " << recall << ", Precision: " << precision << ", IoU: " << iou << endl;
Gives the error:
0xC0000005: Access violation reading location 0x3F09C003.
The weird thing is, this only occurs if I am printing a variable, and it always occurs at the 211th iteration. If I remove the print statement completely, or even just print a string, it works fine. But if I print any variable (i, recall, precision, etc.), it throws this exception. It will also throw the same exception if I remove the printing from the loop completely, and just have a single print statement outside of the loop. Any suggestions?
Code below:
template <typename T>
template <typename T2>
void Rect<T>::GetPerformance(const Rect<T2>& actual,
float &iou, float &precision, float &recall) const {
float numDetections = Area();
float numActual = actual.Area();
iou = Overlap(actual);
float numCorrect = iou *(actual.Area() + Area()) / (1 + iou);
precision = numCorrect / numDetections;
recall = numCorrect / numActual;
}
...
In Main
...
Mat frame;
Mat newFrame;
int i = 0;
float recall;
float precision;
float iou;
float avgRecall = 0;
float avgPrecision = 0;
float avgIoU = 0;
while (1)
{
iFrame = cvQueryFrame(capture);
if (!iFrame) break;
frame = iFrame;
FloatRect bb = carTracker.Track(frame);
bb.GetPerformance(gts[i], iou, precision, recall);
avgRecall += recall;
avgPrecision += precision;
avgIoU += iou;
cout << "Frame " << i << ", Recall: " << recall << ", Precision: " << precision << ", IoU: " << iou << endl;
i++;
}
Related
I am trying to compute the time history of the velocity described by the equation:
dV/dt = g − (C_d/m) * V^2. g = 9.81, m = 1.0, and C_d = 1.5.
To do this I need to create a program in c++ that uses the Euler explicit method to numerically solve the equation. I am trying to find the velocity from t = 0 to t = 1 seconds with three different step sizes of delta_t = 0.05, 0.1, and 0.2 seconds. And then you are supposed to show your percent error to the analytical solution given as: V(t) = sqrt((m*g)/C_d) * tanh(sqrt((g*C_d)/m) * t).
My problem is I am not sure how to iterate through Euler's method multiple times with different time intervals. So far I have solved the analytical equation, but am unsure where to go from here. If anyone could help point me in the right direction it would be greatly appreciated.
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
int main() {
double m = 1.0; // units in [kg]
double g = 9.81; // units in [m/s^2]
double C_d = 1.5; // units in [kg/m]
double t; // units in [s]
double v; // units in [m/s]
cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << endl;
cout << "Please select either 0.05, 0.1, or 0.2 to be the time interval:" << endl;
cin >> t;
cout << "You have chosen the time interval of: " << t << " seconds." << endl;
v = sqrt((m * g) / C_d) * tanh(sqrt((g * C_d) / m) * t);
cout << "The velecity at a time of "<< t << " seconds is equal to: " << v << " m/s." << endl;
return 0;
} ```
If you want to iterate over t with increments of A, calculating the result of the formula with each t, you would write a for loop.
#include <iostream>
int main()
{
double m = 1.0; // units in [kg]
double g = 9.81; // units in [m/s^2]
double C_d = 1.5; // units in [kg/m]
std::cout << "The velocity will be examined from the time t = 0 to t = 1 seconds." << std::endl;
std::cout << "Please select the time interval:" << std::endl;
std::cout << "1: 0.05" << std::endl;
std::cout << "2: 0.1" << std::endl;
std::cout << "3: 0.2" << std::endl;
double A = 0; // increment in for loop
int x;
std::cin >> x;
switch (x) { // check what the input is equal to
case 1: A = 0.05; break;
case 2: A = 0.1; break;
case 3: A = 0.2; break;
default: std::cout << "Unknown option!" << std::endl; return 1;
}
std::cout << "You have chosen the time interval of: " << A << " seconds." << std::endl;
std::cout << "Results of V(t):" << std::endl;
// this initializes a variable t as 0,
//and while t is lower than or equal to 1,
//it will increment it by a and execute the logic within the scope of the loop.
for (double t = 0; t < (1 + A); t += A) {
std::cout << "at t = " << t << ": " << sqrt((m*g) / C_d) * tanh(sqrt((g*C_d) / m) * t) << std::endl;
}
return 0;
}
Refer to https://beginnersbook.com/2017/08/cpp-for-loop/ for more information. Note: I've also introduced a switch statement into the code to prevent unknown values from being input. https://beginnersbook.com/2017/08/cpp-switch-case/
I have been searching on Google an in this forum for a while, but I could not find any answer or tip for my problem. Tutorials couldn't help me either...
I want to redistribute some points, stored in a vector p_org. (x-value is stored as double).
Therefore I have the function distribute, which is defined in maths.h
distribute_tanh(&p_org_temp,&p_new_temp,iz,spacing[0],spacing[1],l_rot[(kk+1)*iz-2],status);
The function distribute_tanh does look like this:
inline void distribute_tanh (std::vector<double> *p_org, std::vector<double> *p_new, const int n_points, double spacing_begin, double spacing_end, const double total_length, double status){
//if status == 0: FLAP, if status == 1: SLAT
std::cout << "spacing_begin: " << spacing_begin << " spacing_end: " << spacing_end << std::endl;
double s_begin = spacing_begin / total_length;
double s_end = spacing_end / total_length;
double A = sqrt(s_end/s_begin);
double B = 1 / (sqrt(s_end*s_begin)*n_points);
std::cout << "A: " << A << " B: " << B << std::endl;
std::vector<double> u (n_points);
std::vector<double> sn (n_points);
double dx;
double dy;
std::cout << "Control at the beginning: p_org: " << (p_org) << " p_new: " << (p_new) << " n_points: " << n_points << " s_begin: " << s_begin << " s_end: " << s_end << " total_length: " << total_length << std::endl;
//problem no. 1
for (int i=0;i<n_points;i++){
if (B > 1.001) {
if (B < 2.7829681) {
double Bq=B-1;
dy=sqrt(6*Bq)*(1-0.15*Bq+0.057321429*pow(Bq,2)-0.024907295*pow(Bq,3)+0.0077424461*pow(Bq,4)-0.0010794123*pow(Bq,5));
} else if (B > 2.7829681) {
double Bv=log(B);
double Bw=1/B-0.028527431;
dy=Bv+(1+1/Bv)*log(2*Bv)-0.02041793+0.24902722*Bw+1.9496443*pow(Bw,2)-2.6294547*pow(Bw,3)+8.56795911*pow(Bw,4);
}
u[i]=0.5+(tanh(dy*(i*(1.0/n_points)-0.5))/(2*tanh(dy/2)));
}
else if (B < 0.999) {
if (B < 0.26938972) {
dx=M_PI*(1-B+pow(B,2)-(1+(pow(M_PI,2))/6)*pow(B,3)+6.794732*pow(B,4)-13.205501*pow(B,5)+11.726095*pow(B,6));
} else if (B > 0.26938972) {
double Bq=1-B;
dx=sqrt(6*Bq)*(1+0.15*Bq+0.057321429*pow(Bq,2)+0.048774238*pow(Bq,3)-0.053337753*pow(Bq,4)+0.075845134*pow(Bq,5));
}
u[i]=0.5+(tan(dx*(i*(1.0/n_points)-0.5))/(2*tan(dx/2)));
}
else {
u[i]=i*(1.0/n_points)*(1+2*(B-1)*(i*(1.0/n_points)-0.5)*(1-i*(1.0/n_points)));
}
sn[i]=u[i]/(A+(1.0-A)*u[i]);
std::cout << "sn(i): " << sn[i] << std::endl;
std::cout << "p_org[n_points]: " << &p_org[n_points-1] << std::endl;
if(status==0){
//p_new[i]=p_org[0]+(total_length*sn[i]);
std::cout << "FLAP maths.h" << std::endl;
}
//Here is the problem no. 2
else if(status==1){
//p_new[i]=p_org[0]-(total_length*sn[i]);
std::cout << "SLAT maths.h" << std::endl;
}
//std::cout << "p_new in math: " << p_new << std::endl;
}
}
My problem is, that I am unable to access the value of p_org or p_new. At the beginning I would like to give out the value of p_org and p_new. If I try it with a *, the compiler is complaining: error: no operator "<<" matches these operands
operand types are: std::basic_ostream> << std::vector>
std::cout << "Control at the beginning: p_org: " << (*p_org) << " p_new: " << (*p_new) << " n_points: " << n_points << " s_begin: " << s_begin << " s_end: " << s_end << " total_length: " << total_length << std::endl;
If I leave the * off, I get the addresses of p_org and p_new.
At the end of the code I would like to write the new value to p_new. If I use * to access the value, the compiler is complaining, if I leave it off, its complaining too with the following message:
error: no operator "-" matches these operands
operand types are: std::vector<double, std::allocator<double>> - double
p_new[i]=p_org[0]-(total_length*sn[i]);
^
I tried to understand both problems, but until now I had no success.
Thanks for your advice.
Your issue with the compiler error can be cut down to a very simple program.
#include <vector>
void foo(std::vector<int>* pV)
{
pV[0] = 10; // error.
}
int main()
{
std::vector<int> v(10);
foo(&v);
}
The issue is that operator[] as done above works for objects and references, not pointers. Since pv is a pointer, you must dereference it first to obtain the object, and then apply [] to the dereferenced pointer.
void foo(std::vector<int>* pV)
{
(*pV)[0] = 10; // No error
}
The other form of calling operator[] can be also used, but is a bit more verbose:
void foo(std::vector<int>* pV)
{
pv->operator[](0) = 10; // No error
}
However, to alleviate having to do this, pass the vector by reference. Then the "normal" way of using operator[] can be used.
#include <vector>
void foo(std::vector<int>& pV)
{
pV[0] = 10; // No error.
}
int main()
{
std::vector<int> v(10);
foo(v);
}
I'm sure I'm doing something wrong, but I just can't figure it out. I've created an object with integer data members, and I want to have a member function return the quotient of it's members as a floating point value, which it does. It then appends some additional stuff. The output is below the program, which should run as is.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Rational
{
public:
explicit Rational(int = 0, int = 1);
double getRationalAsDouble() const;
private:
int numerator;
int denominator;
};
Rational::Rational(int numerator, int denominator)
{
if (denominator == 0)
this->denominator = 1;
else
this->denominator = denominator;
this->numerator = numerator;
}
// ******* Problem Function *********
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << endl << "a = " << a;
cout << endl << "b = " << b;
cout << endl << "a/b = " << (a/b);
}
// ******** End Problem Function ********
int main()
{
{ //Create a new Scope so that I can view Destructor Message, not used here
Rational c(2, 6);
int data = 10;
cout << c.getRationalAsDouble(); // prints rational object c as double, but not really
cout << "\n\n";
} // End of Scope
return 0;
} // end main
And here's the output:
a = 2
b = 6
a/b = 0.3333332.31196e-317
I've been playing around, and if I change the function to have any regular division in it, it works fine. What's really interesting is if I add any output after the cout << endl << "a/b = " << (a/b); line, that output is handled before (a/b) part of the line. Any help would be greatly appreciated! Thank you in advance for your time.
Solution:
The function wasn't returning anything. When the code was changed to:
double Rational::getRationalAsDouble()
{
return static_cast<double>(numerator)/denominator;
}
It worked as expected. Thank you tc.
Three problems:
You want to print endl at the end of the line, not the "beginning". Your code ends up doing (effectively) cout << endl << "a/b = " << (a/b); ... cout << c.getRationalAsDouble(); cout << "\n\n"; which prints the two doubles 0.333333 and 2.31196e-317 next to each other with no space.
You want (perhaps) cout << "\n" << endl instead of cout << "\n\n". endl causes the stream to be flushed; plain "\n" might not.
Rational::getRationalAsDouble() is not returning a value. Listen to your compiler warnings.
The fix looks something like
double Rational::getRationalAsDouble() const
{
double a = 0.0, b = 0.0;
a = static_cast<double>(numerator);
b = static_cast<double>(denominator);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a/b = " << (a/b) << endl;
return a/b;
}
Your implementation of Rational::getRationalAsDouble() can be simplified to:
double Rational::getRationalAsDouble() const
{
return 1.0*numerator/denominator;
}
I think you had everything else there for debugging purposes, and hence are not really needed.
I was wondering if anyone could help me with a more elegant way to code this program that I am writing please. The code I have is bellow, I would like to know if there is a way to separate the part that prints out the totals into a new function. I have tried but I always just get the total is 0, so I must be passing things wrong or something.
void printNumbers(int x, double y, double z, double v, int sum, double sum2,int sum3,int sum4){
while(x != 0){
y = sqrt (x);
z = pow (x,2);
v = pow (x,3);
sum = sum + x;
sum2 = sum2 + y;
sum3 = sum3 + z;
sum4 = sum4 + v;
cout << " " << x << setw(12) << setprecision (4) << y << setw(8) << z << setw(8) << v << endl;
x--;
}
cout << " total is" << sum << setw(12) << sum2 << setw(8)<< sum3 << setw(8) << sum4 << endl;
}
This is what I tried, at the time I only had one total to get, but It still did not work just gave the answer 0:
void printFooters(int sum){
cout << " " << "====================================="<< endl;
cout << "Totals " << sum << endl << endl;
cout << " " << "====================================="<< endl;
}
This is how I was calling it in main():
printFooters(sum);
You need to make the sums into references if you want them to be updated.
void printNumbers(int x, double y, double z, double v, int& sum, double& sum2,int& sum3,int& sum4)
If you don't the sums are passed by value, so you just get a copy of the current value of the sums.
Alternatively you can use pointers to the sums, but that would involve changing the syntax when accessing the sum variables.
You should decide first, what variables are input and what variables should carry output. Try to not use one variable for both input and output, it is often more confusing than valuable.
Only input value is x. Everything else is output values. In way you have used that values, content of values is modified only in local copy inside function printNumbers(). They will get lost on end of function. I expect you want to output computed results from function (however then printNumbers is wrong name for that function).
C and C++ always pass variables to function parameters by value. That means, variable is initialized from parameter, but any changes are done only inside function. At the end of function, copy is discarded and will NOT change anything you passed to it.
If you want output from function, you can use return, or use pointers or references to a variable. I suggest to use references in C++, they are easier to understand and easier to use.
Use references instead of copied variables in function. Then, when you modify that value inside function, it will keep modified value after function return.
void f1(int in, int out)
{
out = in + 1;
}
void f2(int in, int &out)
{
out = in + 1;
}
int o1=-1, o2=-1;
f1(1, o1);
f2(1, o2);
cout << o1 << "," << o2 << endl; // will print -1,2
So declare your function as:
void printNumbers(int x, double &y, double &z, double &v, int &sum, double &sum2,int &sum3,int &sum4);
you can then do:
double y,z;
int sum, sum2, sum3, sum4;
printNumbers(4, y, z, sum, sum2, sum3, sum4);
printFooters(sum);
And this time, it should print whatever printNumbers computed. See http://www.cprogramming.com/tutorial/references.html for a bit more, or use google.
You could batch all those parameters into structs, and separate all the calculations and outputs.
This is probably overkill in your case, and is quite a bit of code, but anyway...
struct Powers
{
double sqroot;
int one;
double square;
double cube;
};
Powers calculatePowers(int x)
{
Powers powers;
powers.sqroot = sqrt(x);
powers.one = x;
powers.square = x * x;
powers.cube = x * x * x;
return powers;
}
struct Sums
{
int sum1;
double sum2;
int sum3;
int sum4;
};
Sums addPowers(Sums sums, Powers powers)
{
sums.sum1 += powers.one;
sums.sum2 += powers.sqroot;
sums.sum3 += powers.square;
sums.sum4 += powers.cube;
return sums;
}
void printPowers(Powers powers)
{
cout << " " << powers.one
<< setw(12) << setprecision (4) << powers.sqroot
<< setw(8) << powers.square
<< setw(8) << powers.cube
<< endl;
}
void printTotals(Sums sums)
{
cout << " total is"
<< sums.sum1
<< setw(12) << sums.sum2
<< setw(8) << sums.sum3
<< setw(8) << sums.sum4
<< endl;
}
void doEverything(int x)
{
Sums sums = {0, 0, 0, 0};
while (x > 0)
{
Powers powers = calculatePowers(x);
printPowers(powers);
sums = addPowers(sums, powers);
x--;
}
printTotals(sums);
}
So I'm having what seems to me to be a very bizarre problem. I've got a crude system for applying forces to objects on 2D planes, and one of the simplest calculations seems to be causing one of my variables to overflow. I have the following line:
int ySign = m_Momentum.y / abs(m_Momentum.y);
Where Momentum has two data members, x y (m_Momentum is an SFML sf::Vector2 of floats). Now, normally the formula should always return either 1 or -1, depending on the sign of Momentum.y (unless I'm grossly mistaken).
However, it occasionally returns insanely high numbers such as -2147483648. In that particular case, the value of m_Momentum.y was 0.712165 (both values were obtained by sending to std::cout); I tried again, m_Momentum.y was -0.578988 and ySign was still -2147483648. There is a corresponding xSign that also flips out sometimes, often with the same final value. I can't confirm 100% that this is always the result, but at the moment that seems to be the case.
I'm sort of stumped as to why this is happening, and when it does, it basically invalidates my program (it instantly sends objects millions of pixels in the wrong direction). It seems logically impossible that the line above is returning such strange results.
Below is the function I am working on. Probably the wrong way to do it, but I didn't expect it to go so horribly wrong. The printout it produces reveals that all numbers look normal until the signs are printed out; one of them is invariably massive, and afterwards you see numbers like -2.727e+008 (which, as far as I'm aware, is scientific notation - i.e. -2.727 * 10 ^ 8).
///MODIFY MOMENTUM
//Reset, if necessary
if (Reset == true)
{
m_Momentum.x = 0;
m_Momentum.y = 0;
}
sf::Vector2<float> OldMoment = m_Momentum;
//Apply the force to the new momentum.
m_Momentum.x += Force.x;
m_Momentum.y += Force.y;
sf::Vector2<float> NewMoment = m_Momentum;
//Calculate total momentum.
float sqMomentum = m_Momentum.x * m_Momentum.x + m_Momentum.y * m_Momentum.y;
float tMomentum = sqrt(sqMomentum);
//Preserve signs for later use.
int xSign = m_Momentum.x / abs(m_Momentum.x);
int ySign = m_Momentum.y / abs(m_Momentum.y);
//Determine more or less the ratio of importance between x and y components
float xProp;
float yProp;
if (abs(tMomentum) > m_MaxVelocity)
{
//Get square of maximum velocity
int sqMax = m_MaxVelocity * m_MaxVelocity;
//Get proportion of contribution of each direction to velocity
xProp = (m_Momentum.x * m_Momentum.x) / sqMomentum;
yProp = (m_Momentum.y * m_Momentum.y) / sqMomentum;
//Reset such that the total does not exceed maximum velocity.
m_Momentum.x = sqrt(sqMax * xProp) * xSign;
m_Momentum.y = sqrt(sqMax * yProp) * ySign;
}
///SANITY CHECK
//Preserve old tMomentum
float tOld = tMomentum;
//Calculate current tMomentum
sqMomentum = m_Momentum.x * m_Momentum.x + m_Momentum.y * m_Momentum.y;
tMomentum = sqrt(sqMomentum);
//If it's still too high, print a report.
if (tMomentum > m_MaxVelocity)
{
std::cout << "\n\nSANITY CHECK FAILED\n";
std::cout << "-\n";
std::cout << "Old Components: " << OldMoment.x << ", " << OldMoment.y << "\n";
std::cout << "Force Components: " << Force.x << ", " << Force.y << "\n";
std::cout << "-\n";
std::cout << "New Components: " << NewMoment.x << ", " << NewMoment.y << "\n";
std::cout << "Which lead to...\n";
std::cout << "tMomentum: " << tOld << "\n";
std::cout << "-\n";
std::cout << "Found these proportions: " << xProp << ", " << yProp << "\n";
std::cout << "Using these signs: " << xSign << ", " << ySign << "\n";
std::cout << "New Components: " << m_Momentum.x << ", " << m_Momentum.y << "\n";
std::cout << "-\n";
std::cout << "Current Pos: " << m_RealPosition.x << ", " << m_RealPosition.y << "\n";
std::cout << "New Pos: " << m_RealPosition.x + m_Momentum.x << ", " << m_RealPosition.y + m_Momentum.y << "\n";
std::cout << "\n\n";
}
///APPLY FORCE
//To the object's position.
m_RealPosition.x += m_Momentum.x;
m_RealPosition.y += m_Momentum.y;
//To the sprite's position.
m_Sprite.Move(m_Momentum.x, m_Momentum.y);
Can somebody explain what's going on here?
EDIT: RedX helpfully directed me to the following post: Is there a standard sign function (signum, sgn) in C/C++? Which led me to write the following lines of code:
//Preserve signs for later use.
//int xSign = m_Momentum.x / abs(m_Momentum.x);
//int ySign = m_Momentum.y / abs(m_Momentum.y);
int xSign = (m_Momentum.x > 0) - (m_Momentum.x < 0);
int ySign = (m_Momentum.y > 0) - (m_Momentum.y < 0);
Thanks to the above, I no longer have the strange problem. For an explanation/alternative solution, see Didier's post below.
You should use fabs() instead of abs() to get the absolute value of a floating point number. If you use the integer absolute function, then the result is an integer ...
For instance, -0.5 / abs(-0.5) is treated as -0.5 / 0 which results in negative infinity (as a floating point value) that is converted to the minimum value of an int 0x80000000 = -2147483648
Taking absolute values and dividing sounds like an awful waste of cycles to me. What's wrong with
x > 0 ? 1 : -1
which you could always put in a function
template <class T>
inline int sgn(const T &x) { return x > 0 ? : 1; }