what is wrong with my cross product code - c++

I am a C++ beginner. I would like to get the normal vector of a surface, which is determined by three point a,b and c. I have the following code, but I do not know what is wrong with it. Thanks for the help.
#include <iostream>
using namespace std;
class point
{
public:
double x,y,z;
};
class crproduct:point
{
public:
double x1,x2,x3,y1,y2,y3,z1,z2,z3,Ax,Ay,Az,Bx,By,Bz;
point crproduc(point *a,point *b,point *c)
{
//point a
x1 = (*a).x;
y1 = (*a).y;
z1 = (*a).z;
//point b
x2 = (*b).x;
y2 = (*b).y;
z2 = (*b).z;
//point c
x3 = (*c).x;
y3 = (*c).y;
z3 = (*c).z;
//Vector A
Ax = x1-x2;
Ay = y1-y2;
Az = z1-z2;
//vector B
Bx = x2-x3;
By = y2-y3;
Bz = z2-z3;
//cross product
point vector;
vector.x = (Ay*Bz)-(By*Az);
vector.y = -(Ax*Bz)+(Bx*Az);
vector.z = (Ax*By)-(Ay*Bx);
return vector;
}
};
int main ()
{
point *pp, *p1, *p2;
point cd;
crproduct cr1,cr2,cr3,cr4;
(*pp).x = 12;
(*pp).y = 13;
(*pp).z = 15
(*p1).x = 10;
(*p1).y = 10;
(*p1).z = 10;
(*p2).x = 8;
(*p2).y = 5;
(*p2).z = 2;
cd = cr1.crproduc(pp,p1,p2);
cout << cd.x << " " << cd.y << " " << cd.z << endl;
system("pause");
return 0;
}

This is incorrect:
point *pp,*p1,*p2;
point cd;
crproduct cr1,cr2,cr3,cr4;
(*pp).x=12;
(*pp).y=13;
(*pp).z=15
(*p1).x=10;
(*p1).y=10;
(*p1).z=10;
(*p2).x=8;
(*p2).y=5;
(*p2).z=2;
Apart from the missing semicolon, the point *pp,*p1,*p2 line establishes three typed pointers. It doesn't create any objects or instantiate the pointers. So at that point, using the pointers will have undefined results.
You then go on to access the pointers.
If you want them on the stack, just declare the objects directly as:
point pp, p1, p2;
... and then access appropriately. If you need them on the heap then you should use new to create objects that the pointers can point to, e.g.
pp = new point;
And don't forget to delete later.

Related

C++: In which order class members are updated and passed to the base class constructor (before it gets called) in Initializer List? [duplicate]

This question already has answers here:
Order of calling base class constructor from derived class initialization list
(3 answers)
Are parent class constructors called before initializing variables?
(7 answers)
Closed 2 years ago.
In my code, there are two classes:
Vect3 which represents a vector in 3D i.e. x, y & z
Plane which represents the coefficients in the equation of plane i.e. a, b, c, & d
Now, Vect3 is my base class and Plane is the derived one.
Vect3 class (base class):
class Vect3 {
public:
Vect3(float x, float y, float z);
Vect3(std::vector<float> vec);
void printVect3() const;
void printVect3Magnitude() const;
void printAngleWrtAxisDeg();
float rad2deg(float angle_in_rad);
protected:
float _x = 0.0;
float _y = 0.0;
float _z = 0.0;
float _magnitude = 0.0;
float _angle_wrt_X = 0.0;
float _angle_wrt_Y = 0.0;
float _angle_wrt_Z = 0.0;
void _doCalculation();
};
Vect3::Vect3(float x, float y, float z) : _x(x), _y(y), _z(z) {
_doCalculation();
}
Vect3::Vect3(std::vector<float> vec) : _x(vec[0]), _y(vec[1]), _z(vec[2]) {
_doCalculation();
}
void Vect3::_doCalculation() {
_magnitude = sqrt(_x * _x + _y * _y + _z * _z);
_angle_wrt_X = acos(_x / _magnitude);
_angle_wrt_Y = acos(_y / _magnitude);
_angle_wrt_Z = acos(_z / _magnitude);
}
void Vect3::printVect3() const {
std::cout << "x = " << _x << " | y = " << _y << " | z = " << _z << "\n";
}
void Vect3::printVect3Magnitude() const {
std::cout << _magnitude << "\n";
}
void Vect3::printAngleWrtAxisDeg() {
std::cout << "Angle in degree, "
<< "wrt X-axis = " << rad2deg(_angle_wrt_X)
<< " | wrt Y-axis = " << rad2deg(_angle_wrt_Y)
<< " | wrt Z-axis = " << rad2deg(_angle_wrt_Z) << "\n";
}
float Vect3::rad2deg(float angle_in_rad) {
return (angle_in_rad * 180.0 / M_PI);
}
Plane class (derived class):
class Plane : public Vect3 {
public:
Plane(std::vector<float> plane_coefficients);
private:
float _a = 0.0;
float _b = 0.0;
float _c = 0.0;
float _d = 0.0;
};
Plane::Plane(std::vector<float> plane_coefficients) : _a(plane_coefficients[0]), _b(plane_coefficients[1]), _c(plane_coefficients[2]), _d(plane_coefficients[3]), Vect3(_a, _b, _c) {
std::cout << "from Plane class: " << _x << " " << _y << " " << _z << "\n";
}
However, for the following main,
int main() {
std::vector<float> vec1 = {1.0, 1.0, 1.0, 1.0};
Plane plane1(vec1);
plane1.printVect3Magnitude();
plane1.printAngleWrtAxisDeg();
std::cout << "= = = = = = = = = = = =\n";
Vect3 vect3d(vec1);
vect3d.printVect3Magnitude();
vect3d.printAngleWrtAxisDeg();
return 0;
}
I'm getting somewhat weird output:
from Plane class: 3.07795e-41 2.8026e-45 0
0
Angle in degree, wrt X-axis = nan | wrt Y-axis = nan | wrt Z-axis = -nan
= = = = = = = = = = = =
1.73205
Angle in degree, wrt X-axis = 54.7356 | wrt Y-axis = 54.7356 | wrt Z-axis = 54.7356
In the plane constructor, using initializer list, I'm already updating _a, _b, & _c first and then passing them to Vect3 constructor.
So, ideally, output of printVect3Magnitude() & printAngleWrtAxisDeg() method of object plane and object vect3d should be same.
However, based on the above output, it looks like garbage values are being passed to Vect3 constructor!!
On the other hand, if I modify plane constructor as follow (i.e. rather than passing _a, _b, _c to Vect3 constructor, directly pass input vector plane_coefficients)
Plane::Plane(std::vector<float> plane_coefficients) : _a(plane_coefficients[0]), _b(plane_coefficients[1]), _c(plane_coefficients[2]), _d(plane_coefficients[3]), Vect3(plane_coefficients) {
std::cout << "from Plane class: " << _x << " " << _y << " " << _z << "\n";
}
then I'm getting the expected output:
from Plane class: 1 1 1
1.73205
Angle in degree, wrt X-axis = 54.7356 | wrt Y-axis = 54.7356 | wrt Z-axis = 54.7356
= = = = = = = = = = = =
1.73205
Angle in degree, wrt X-axis = 54.7356 | wrt Y-axis = 54.7356 | wrt Z-axis = 54.7356
But why? Am I mistaken regarding the order in which the class members are being updated and passed to the base class constructor (before it gets called) in the initializer list?
Did you notice the compiler warnings?
Regardless of how you order the members and base classes in the constructor initializer list, they will be constructed in the declaration order and destructed in the reverse declaration order. Since base list is declared before the block that nests all members, all base sub-objects precede members while construction. If - in the constructor initializer list - the initializer for members and/or bases is miss-placed, a diagnostic warning is generated, but the code compiles . And if a member or base is initialized to the value of another base/member declared after itself, UB will result - as the OP has already observed.
Best,
FM.

How to get the indices of the optimal basis using Gurobi through a C++ code

I am calling Gurobi through a c++ program to solve a linear program and I need to extract the indices of the optimal base.
#include "gurobi_c++.h"
#include <stdlib.h>
using namespace std;
#include<vector>
int
main(int argc,
char *argv[])
{
try {
GRBEnv env = GRBEnv();
GRBModel model = GRBModel(env);
// Create variables
GRBVar x1 = model.addVar(0.0, GRB_INFINITY , 0.0, GRB_CONTINUOUS, "x1");
GRBVar x2 = model.addVar(0.0, GRB_INFINITY , 0.0, GRB_CONTINUOUS, "x2");
// Set objective
// model.setObjective(4 * x1 + 6 * x2, GRB_MAXIMIZE);
model.setObjective(2 * x1 - 5 * x2, GRB_MAXIMIZE);
// Add constraints
model.addConstr(2 * x1 + 3 * x2 <= 30, "c0");
model.addConstr(4 * x1 - 9 * x2 <= 0, "c1");
model.addConstr(x1 + x2 >= 5, "c2");
// Optimize model
model.optimize();
//get the indices of the optimal base
int nbColumns = 3;
int nbLines = 2;
int * bhead = (int *) malloc (nbLines);
for (int i = 0; i < nbLines; ++i)
{
bhead[i] = -1;
}
GRBModel *p_model = &model;
int b = GRBgetBasisHead(p_model, bhead);
cout<<"base 1"<<bhead[0]<<endl;
cout<<"base 2"<<bhead[1]<<endl;;
cout<<"base 3"<<bhead[2]<<endl;
} catch(GRBException e) {
cout << "Error code = " << e.getErrorCode() << endl;
cout << e.getMessage() << endl;
} catch(...) {
cout << "Exception during optimization" << endl;
}
return 0;
}
I get an error when I try to use GRBgetBasisHead which is defined in the C API, the error is:
error: cannot convert ‘GRBModel*’ to ‘GRBmodel* {aka _GRBmodel*}’ for argument ‘1’ to ‘int GRBgetBasisHead(GRBmodel*, int*)’
Because in C++ API the models are constructed using GRBModel and in C API the models are constructed using GRBmodel. In the other hand, there is VBasis that gives the status of a variable in the current basis, but in this case we need to test the status of all the variables to find the indices of the optimal base. My question is: is there a way to get directly the indices of the optimal base?

Access variables in a struct?

I'm building a small vector engine and I'm having some trouble accessing the variables I have made in my struct.
Here's my struct:
struct vectorVariables {
float v = 0, a = 0;
float u = 20;
float deltaT = 0.01;
float posNew = 0 , posOld = 0;
float gravity = -9.81;
};
All I want to be able to do for example, is print out one of these variables to the console.
Those variables are available if you create an object. With that declaration in scope, and with the appropriate headers included, try this:
int main() {
vectorVariables vv;
std::cout << vv.v << " " << vv.a << "\n";
}

Moving from (bad) array[size] to array = new float[size]

I was writing a program for finding roots for a class, and had finished and got it working perfectly. As I go to turn it in, I see the document requires the .cpp to compile using Visual Studio 2012 - so I try that out. I normally use Dev C++ - and I've come to find it allows me to compile "funky things" such as dynamically declaring arrays without using malloc or new operators.
So, after finding the error associated with how I wrongly defined my arrays - I tried to fix the problem using malloc, calloc, and new/delete and well - it kept giving me memory allocation errors. The whole 46981239487532-byte error.
Now, I tried to "return" the program to the way it used to be and now I can't even get that to work. I'm not even entirely sure how I set up the arrays to work in Dev C++ in the first place. Here the code:
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
float newton(float a, float b, float poly[],float n, float *fx, float *derfx);
float horner(float poly[], int n, float x, float *derx);
float bisection(float a, float b, float poly[], float n, float *fx);
int main(int argc, char *argv[])
{
float a, b, derr1 = 0, dummyvar = 0, fr1 = 0, fr0;
float constants[argc-3];
//float* constants = NULL;
//constants = new float[argc-3];
//constants = (float*)calloc(argc-3,sizeof(float));
//In order to get a and b from being a char to floating point, the following lines are used.
//The indexes are set relative to the size of argv array in order to allow for dynamically sized inputs. atof is a char to float converter.
a = atof(argv[argc-2]);
b = atof(argv[argc-1]);
//In order to get a easy to work with array for horners method,
//all of the values excluding the last two are put into a new floating point array
for (int i = 0; i <= argc - 3; i++){
constants[i] = atof(argv[i+1]);
}
bisection(a, b, constants, argc - 3, &fr0);
newton(a, b, constants, argc - 3, &fr1, &derr1);
cout << "f(a) = " << horner(constants,argc-3,a,&dummyvar);
cout << ", f(b) = " << horner(constants,argc-3,b,&dummyvar);
cout << ", f(Bisection Root) = " << fr0;
cout << ", f(Newton Root) = "<<fr1<<", f'(Newton Root) = "<<derr1<<endl;
return 0;
}
// Poly[] is the polynomial constants, n is the number of degrees of the polynomial (the size of poly[]), x is the value of the function we want the solution for.
float horner(float poly[], int n, float x, float *derx)
{
float fx[2] = {0, 0};
fx[0] = poly[0]; // Initialize fx to the largest degree constant.
float derconstant[n];
//float* derconstant = NULL;
//derconstant = new float[n];
//derconstant = (float*)calloc(n,sizeof(float));
derconstant[0] = poly[0];
// Each term is multiplied by the last by X, then you add the next poly constant. The end result is the function at X.
for (int i = 1; i < n; i++){
fx[0] = fx[0]*x + poly[i];
// Each itteration has the constant saved to form the derivative function, which is evaluated in the next for loop.
derconstant[i]=fx[0];
}
// The same method is used to calculate the derivative at X, only using n-1 instead of n.
fx[1] = derconstant[0]; // Initialize fx[1] to the largest derivative degree constant.
for (int i = 1; i < n - 1; i++){
fx[1] = fx[1]*x + derconstant[i];
}
*derx = fx[1];
return fx[0];
}
float bisection(float a, float b, float poly[], float n, float *fx)
{
float r0 =0, count0 = 0;
float c = (a + b)/2; // c is the midpoint from a to b
float fc, fa, fb;
int rootfound = 0;
float *derx;
derx = 0; // Needs to be defined so that my method for horner's method will work for bisection.
fa = horner(poly, n, a, derx); // The following three lines use horner's method to get fa,fb, and fc.
fb = horner(poly, n, b, derx);
fc = horner(poly, n, c, derx);
while ((count0 <= 100000) || (rootfound == 0)) { // The algorithm has a limit of 1000 itterations to solve the root.
if (count0 <= 100000) {
count0++;
if ((c == r0) && (fabs(fc) <= 0.0001)) {
rootfound=1;
cout << "Bisection Root: " << r0 << endl;
cout << "Iterations: " << count0+1 << endl;
*fx = fc;
break;
}
else
{
if (((fc > 0) && (fb > 0)) || ((fc < 0) && (fb < 0))) { // Checks if fb and fc are the same sign.
b = c; // If fc and fb have the same sign, thenb "moves" to c.
r0 = c; // Sets the current root approximation to the last c value.
c = (a + b)/2; // c is recalculated.
}
else
{
a=c; // Shift a to c for next itteration.
r0=c; // Sets the current root approximation to the last c value.
c=(a+b)/2; // Calculate next c for next itteration.
}
fa = horner(poly, n, a, derx); // The following three send the new a,b,and c values to horner's method for recalculation.
fb = horner(poly, n, b, derx);
fc = horner(poly, n, c, derx);
}
}
else
{
cout << "Bisection Method could not find root within 100000 itterations" << endl;
break;
}
}
return 0;
}
float newton(float a, float b, float poly[],float n, float *fx, float *derfx){
float x0, x1;
int rootfound1 = 1, count1 = 0;
x0 = (a + b)/2;
x1 = x0;
float fx0, derfx0;
fx0 = horner(poly, n, x0, &derfx0);
while ((count1 <= 100000) || (rootfound1 == 0)) {
count1++;
if (count1 <= 100000) {
if ((fabs(fx0) <= 0.0001)) {
rootfound1 = 1;
cout << "Newtons Root: " << x1 << endl;
cout << "Iterations: " << count1 << endl;
break;
}
else
{
x1 = x0 - (fx0/derfx0);
x0 = x1;
fx0 = horner(poly, n, x0, &derfx0);
*derfx = derfx0;
*fx = fx0;
}
}
else
{
cout << "Newtons Method could not find a root within 100000 itterations" << endl;
break;
}
}
return 0;
}
So I've spent the past several hours trying to sort this out, and ultimately, I've given in to asking.Everywhere I look has just said to define as
float* constants = NULL;
constants = new float[size];
but this keeps crashing my programs - presumably from allocating too much memory somehow. I've commented out the things I've tried in various ways and combonations. If you want a more tl;dr to the "trouble spots", they are at the very beginning of the main and horner functions.
Here is one issue, in main you allocate space for argc-3 floats (in various ways) for constants but your code in the loop writes past the end of the array.
Change:
for( int i = 0; i<=argc-3; i++){
to
for( int i = 0; i<argc-3; i++){
That alone could be enough to cause your allocation errors.
Edit: Also note if you allocate space for something using new, you need to delete it with delete, otherwise you will continue to use up memory and possibly run out (especially if you do it in a loop of 100,000).
Edit 2: As Galik mentions below, because you are using derconstant = new float[n] to allocate the memory, you need to use delete [] derconstant to free the memory. This is important when you start allocating space for class objects as the delete [] form will call the destructor of each element in the array.

structs within structs, dynamic memory allocation

I am making a 3D application where a boat has to drive through buoy tracks. I also need to store the tracks in groups or "layouts". The buoys class is basically a list of "buoy layouts" inside of which is a list of "buoy tracks", inside of which is a list of buoys.
I checked the local variable watcher and all memory allocations in the constructor appear to work. Later when the calculateCoordinates function is called it enters a for loop. On the first iteration of the for loop the functions pointer is used and works fine, but then on this line
ctMain[j+1][1] = 0;
the function pointers are set to NULL. I am guessing it has something to with the structs not being allocated or addressed correctly. I am not sure what to do from here. Maybe I am not understanding how malloc is working.
Update
I replaced the M3DVector3d main_track with double ** main_track, thinking maybe malloc is not handling the typedefs correctly. But I am getting the same error when trying to access the main_track variable later in calculateCoordinates.
Update
It ended up being memory corruption caused by accessing a pointer wrong in the line
rotatePointD(&(cTrack->main_track[j]), rotation);
It only led to an error later when I tried to access it.
// Buoys.h
////////////////////////////////////////////
struct buoy_layout_t;
struct buoy_track_t;
typedef double M3DVector3d[3];
class Buoys {
public:
Buoys();
struct buoy_layout_t ** buoyLayouts;
int nTrackLayouts;
int currentLayoutID;
void calculateCoordinates();
};
struct buoy_track_t {
int nMain, nYellow, nDistract;
M3DVector3d * main_track,
yellow_buoys,
distraction_buoys;
double (*f)(double x);
double (*fp)(double x);
double thickness;
M3DVector3d start, end;
};
struct buoy_layout_t {
int nTracks;
buoy_track_t ** tracks;
};
// Buoys.cpp
/////////////////////////////
// polynomial and its derivative, for shape of track
double buoyfun1(double x) {return (1.0/292.0)*x*(x-12.0)*(x-24.0);}
double buoyfun1d(double x) {return (1.0/292.0)*((3.0*pow(x,2))-(72.0*x)+288.0);}
// ... rest of buoy shape functions go here ...
Buoys::Buoys() {
struct buoy_layout_t * cLayout;
struct buoy_track_t * cTrack;
nTrackLayouts = 1;
buoyLayouts = (buoy_layout_t **) malloc(nTrackLayouts*sizeof(*buoyLayouts));
for (int i = 0; i < nTrackLayouts; i++) {
buoyLayouts[i] = (buoy_layout_t *) malloc(sizeof(*(buoyLayouts[0])));
}
currentLayoutID = 0;
// ** Layout 1 **
cLayout = buoyLayouts[0];
cLayout->nTracks = 1;
cLayout->tracks = (buoy_track_t **) malloc(sizeof(*(cLayout->tracks)));
for (int i = 0; i < 1; i++) {
cLayout->tracks[i] = (buoy_track_t *) malloc (sizeof(*(cLayout->tracks)));
}
cTrack = cLayout->tracks[0];
cTrack->main_track = (M3DVector3d *) malloc(30*sizeof(*(cTrack->main_track)));
cTrack->nMain = 30;
cTrack->f = buoyfun1;
cTrack->fp = buoyfun1d;
cTrack->thickness = 5.5;
cTrack->start[0] = 0; cTrack->start[1] = 0; cTrack->start[2] = 0;
cTrack->end[0] = 30; cTrack->end[1] = 0; cTrack->end[2] = -19;
// ... initialize rest of layouts here ...
// ** Layout 2 **
// ** Layout 3 **
// ...
// ** Layout N **
calculateCoordinates();
}
void Buoys::calculateCoordinates()
{
int i, j;
buoy_layout_t * cLayout = buoyLayouts[0];
for (i = 0; i < (cLayout->nTracks); i++) {
buoy_track_t * cTrack = cLayout->tracks[i];
M3DVector3d * ctMain = cTrack->main_track;
double thickness = cTrack->thickness;
double rotation = getAngleD(cTrack->start[0], cTrack->start[2],
cTrack->end[0], cTrack->end[2]);
double full_disp = sqrt(pow((cTrack->end[0] - cTrack->start[0]), 2)
+ pow((cTrack->end[2] - cTrack->start[2]), 2));
// nBuoys is nBuoys per side. So one side has nBuoys/2 buoys.
for (j=0; j < cTrack->nMain; j+=2) {
double id = j*((full_disp)/(cTrack->nMain));
double y = (*(cTrack->f))(id);
double yp = (*(cTrack->fp))(id);
double normal, normal_a;
if (yp!=0) {
normal = -1.0/yp;
}
else {
normal = 999999999;
}
if (normal > 0) {
normal_a = atan(normal);
}
else {
normal_a = atan(normal) + PI;
}
ctMain[j][0] = id + ((thickness/2.0)*cos(normal_a));
ctMain[j][1] = 0;
ctMain[j][2] = y + ((thickness/2.0)*sin(normal_a));
ctMain[j+1][0] = id + ((thickness/2.0)*cos(normal_a+PI));
ctMain[j+1][1] = 0; // function pointers get set to null here
ctMain[j+1][2] = y + ((thickness/2.0)*sin(normal_a+PI));
}
for (j=0; j < cTrack->nMain; j++) {
rotatePointD(&(cTrack->main_track[j]), rotation);
}
}
}
Unless there are requirements for learning pointers or you cannot use STL, given you are using C++ I'd strongly recommend you use more STL, it is your friend. But anyways...
First, the type of ctMain is *M3DVector3D. So you can safely access ctMain[0], but you cannot access ctMain[1], maybe you meant for the type of ctMain to be **M3DVector3D, in which case the line for initialization you had written which is:
cTrack->main_track = (M3DVector3d *) malloc(30*sizeof(*(cTrack->main_track)));
would make sense.
More Notes
Why are you allocating 30 of these here?
cTrack->main_track = (M3DVector3d *) malloc(30*sizeof(*(cTrack->main_track)));
Given the type of main_track, you only need:
cTrack->main_track = (M3DVector3d *) malloc(sizeof(M3DVector3d));
In addition, for organizational purposes, when doing sizeof you may want to give the actual type to check the sizeof, as opposed to the variable (there should be no difference, just organizational), these two changes:
buoyLayouts = (buoy_layout_t **) malloc(nTrackLayouts*sizeof(buoy_layout_t*));
for (int i = 0; i < nTrackLayouts; i++) {
buoyLayouts[i] = (buoy_layout_t *) malloc(sizeof(buoy_layout_t));
}
cLayout->tracks = (buoy_track_t **) malloc(clayout->nTracks * sizeof(buoy_track_t*));
for (int i = 0; i < 1; i++) {
cLayout->tracks[i] = (buoy_track_t *) malloc(sizeof(buoy_track_t));
}