Set method in a simple c++ class file returning strange values - c++

I am having trouble using a set function in a class file. So far I have the following. I am trying to write a quadratic class that has three private data members and can calculate both the value of a quadratic and the number of real roots in the quadratic. I'm not stuck on the math part as much as I am getting the set methods to not give me weird values. When I test using main, the values for a, b, and c are numbers that I didn't input when I created the object.
Quadratic.hpp
#ifndef QUADRATIC_HPP
#define QUADRATIC_HPP
class Quadratic
{
private:
double a;
double b;
double c;
public:
Quadratic();
Quadratic(double, double, double);
void setA(double);
void setB(double);
void setC(double);
double getA();
double getB();
double getC();
double valueFor(double);
int numRealRoots();
};
#endif
Quadratic.cpp
#include <cmath>
#include <iostream>
Quadratic::Quadratic()
{
setA(1.0);
setB(1.0);
setC(1.0);
}
Quadratic::Quadratic(double A, double B, double C)
{
a = A;
b = B;
c = C;
}
void Quadratic::setA(double A)
{
a = A;
}
void Quadratic::setB(double B)
{
a = B;
}
void Quadratic::setC(double C)
{
c = C;
}
double Quadratic::getA()
{
return a;
}
double Quadratic::getB()
{
return b;
}
double Quadratic::getC()
{
return c;
}
double Quadratic::valueFor(double x)
{
return (a*(pow(x,2)) + b*x + c);
}
int Quadratic:: numRealRoots()
{
double discriminant = pow(b,2) - (4*a*c);
double epsilon = 0.00001;
int realRoots;
if (discriminant <= epsilon && discriminant > 0)
realRoots = 1;
else if (discriminant > epsilon)
realRoots = 2;
else
realRoots = 0;
return realRoots;
}

Your setB method is wrong - it updates a instead of b:
void Quadratic::setB(double B)
{
b = B; // Was "a = B;" in the original code
}

Related

Errors in implementing an integral function from x to infinity from scratch in CPP with substitution

So I am trying to implement an integration function from scratch in CPP. I have been stuck on this for 2 days.
I am not sure how to do an integration computation from x to +inf. My plan was to use the sigmoid function as a substitution for the integration which should mathematically work but it didn't work computationally. Formula reference: https://en.wikipedia.org/wiki/Integration_by_substitution#Definite_integrals
My questions are 1). why my method didn't work? 2). Is there a better method/function to be used for the substitution?
Reproducible Code
which can be accessed via https://onlinegdb.com/F3rzIEReA with explanations as comments
#include <iostream>
#include <cmath>
const double PI = 3.14159265358979323846;
using namespace std;
// I have an interface for a real function named RealFunction which
// is used to be fed into the integral function
class RealFunction {
public:
virtual ~RealFunction() {};
virtual double evaluate( double x ) = 0;
};
// integral function that utilises the rectangular rule
double integral( RealFunction& f,
double a,
double b,
int nPoints ) {
double h = (b-a)/nPoints;
double x = a + 0.5*h;
double totalHeight = 0.0;
for (int i=0; i<nPoints; i++) {
double height = f.evaluate(x);
totalHeight+=height;
x+=h;
}
return h*totalHeight;
}
// a probability normal distribution function
class NormPDF : public RealFunction {
public:
NormPDF(double mu, double sigma) :
mu(mu), sigma(sigma){}
NormPDF() :
mu(0.0), sigma(1.0){}
double mu;
double sigma;
double evaluate(double x){
return exp(-0.5*pow((x-mu)/sigma,2.0))/(sigma*sqrt(2*PI));
}
};
// my chosen substitution function - sigmoid function
double sigmoidFunction(double x) {
return 1/(1+exp(-x));
}
// implementing the integral to infinity function with
// the sigmoid function
double integralToInfinity( RealFunction& f,
double x,
int nPoints) {
class SigmoidInfusedFunction : public RealFunction {
public:
SigmoidInfusedFunction(RealFunction& f) :
f(f) {
}
RealFunction &f;
double evaluate(double x) {
// d(sig)/dx = exp(-x) / pow(1+exp(-x),2)
return f.evaluate(sigmoidFunction(x)) * exp(-x) / pow(1+exp(-x),2);
}
};
SigmoidInfusedFunction sigmoidInfusedFunc(f);
return integral(sigmoidInfusedFunc, sigmoidFunction(x), 1, 1000);
}
int main() {
// Test for integrate - result: 0.95004 expected: 0.95 (CORRECT)
NormPDF normPDF;
cout << integral(normPDF, -1.96, 1.96, 1000) << endl;
// Test for infinity - result: 0.0688965 expected: 0.5 (INCORRECT)
cout << integralToInfinity(normPDF, 0, 1000) << endl;
return 0;
}

LawOfCosines solving for c, but getting odd answer

I have been trying to code a program that can solve for c using the Law Of Cosines. The program runs correctly, but the answer I get is ridiculously big, noted by how it was in scientific notation.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
class TrigMath
{
private:
double a;
double b;
double y;
public:
double LawOfCos()
{
return sqrt(pow(a,2) + pow(b,2) - 2*a*b*cos(y));
}
void seta(double A)
{
A = a;
}
void setb(double B)
{
B = b;
}
void sety(double Y)
{
Y = y;
}
};
int main()
{
TrigMath triangle1;
triangle1.seta(3);
triangle1.setb(4);
triangle1.sety(60);
cout << "c is equal to " << triangle1.LawOfCos() << endl;
return 0;
}
The cos() function there takes input as radians not as degrees.
Try to convert degrees to radians and then supply it as input.
In the class functions seta, setb and sety you have written A = a, B = b and Y = y.
You have to change them to a = A, b = B and Y = y.
So after applying all the changs the code should be like
#include <iostream>
#include <cmath>
using namespace std;
class TrigMath
{
private:
double a = 0;
double b = 0;
double y = 0;
public:
double LawOfCos()
{
return sqrt(pow(a,2) + pow(b,2) - 2*a*b*cos(y));
}
void seta(double A)
{
a = A;
}
void setb(double B)
{
b = B;
}
void sety(double Y)
{
y = Y*3.14/180;
}
};
int main()
{
TrigMath triangle1;
triangle1.seta(3.0);
triangle1.setb(4.0);
triangle1.sety(60.0);
cout << "c is equal to " << triangle1.LawOfCos() << endl;
return 0;
}

Making an array of function pointers [duplicate]

This question already has answers here:
How define an array of function pointers in C
(5 answers)
Closed 4 years ago.
My problem is: I want to write a program which create an array function pointers. I know how to make pointer to function, but don't know how to make array of them.
This is what I tried up to now:
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a/b; }
int main() {
double(*Padd)(double a, double b);
double(*Psub)(double a, double b);
double(*Pmult)(double a, double b);
double(*Pdiv)(double a, double b);
Padd = &add;
Psub = ⊂
Pmult = &mult;
Pdiv = &div;
}
In my code I create these pointers to functions in an array like e.g.
double Tpointers[3];
Tpointers[0] = Padd;
Tpointers[1] = Psub;
Tpointers[2] = Pmult;
Tpointers[3] = Pdiv;
How do I do this?
Simply declare a new type 'Tpointers' that represent a pointer to a function that give two double and return a double.
And in the code you can create an array of functions.
#include<iostream>
// The function pointer type!
typedef double (*Tpointers)(double, double);
double add(double a, double b) { return a + b; }
double sub(double a, double b) { return a - b; }
double mult(double a, double b) { return a * b; }
double div(double a, double b) { return a / b; }
int main() {
// A functions pointers array .
Tpointers fun_array[4];
// Assign the values
fun_array[0] = &add;
fun_array[1] = ⊂
fun_array[2] = &mult;
fun_array[3] = &div;
// A little test
std::cout << fun_array[2](3, 3) << " " << fun_array[3](3,3) << " " << fun_array[1](3,3)
<< std::endl;
return 0;
}
In c++ you can also create an std::vector of functions pointer ... or any containers from the std libraries of "Tpointers".

Wrapping functions in c++

I have a function executor which is called with function pointer and a general function origin which I wan't to pass with different parameters a and b to the executor. How can it be done?
Here is what I have tried so far:
#include <iostream>
void executor(float (*f)(float)) {
float x = 1.;
std::cout << (*f)(x) << std::endl;
}
float original(float x,float a,float b) {
return a*x + b;
}
//// Works as expected
float a = 1;
float b = 2;
float wrapped(float x) {
return original(x,a,b);
}
void call_executor_global() {
executor(wrapped);
}
//// FIRST TRY
// void call_executor_func(float a, float b) {
// float wrapped(float x) {
// return original(x,a,b);
// }
// executor(wrapped);
// }
//// SECOND TRY
// struct Wrapper {
// float a;
// float b;
// float func(float x) {
// return original(x,a,b);
// }
// };
// void call_executor_struct(float a, float b) {
// Wrapper wrapped;
// wrapped.a = a;
// wrapped.b = b;
// executor(wrapped.func);
// }
int main()
{
call_executor_global();
// call_executor_func(1,2);
// call_executor_struct(1,2);
}
You can wrap a function using several methods. It is easier if you make executor a function template.
template <typename F>
void executor(F f) {
float x = 1.;
std::cout << f(x) << std::endl;
}
Use a global function
float a = 1;
float b = 2;
float wrapped(float x) {
return original(x,a,b);
}
void call_executor_global1() {
executor(wrapped);
}
Use a lambda function
float a = 1;
float b = 2;
void call_executor_global2() {
executor([](float x) {return original(x, a, b);});
}
Use a functor
float a = 1;
float b = 2;
void call_executor_global3() {
struct wrapper
{
float operator()(float x) { return original(x, a, b); }
};
executor(wrapper());
}
See all of them working at http://ideone.com/rDKHC1.

Linking class header, class implementation, and driver issue

I can't seem to get this to work without the driver including the quadratic.cpp file. I have it set up as a project in Dev C++ but keep getting errors saying undefined reference to all of my functions called in the driver.
quadratic.h
#include <iostream>
using namespace std;
class Quadratic{
private:
float a,b,c;
public:
//Quadratic();
Quadratic();
Quadratic(float a,float b,float c);
float x;
float get_a();
float get_b();
float get_c();
float evaluate(float);
void set();
int numRoots(Quadratic &qTest);
float roots1(int numRoots, Quadratic &qRoots);
float roots2(int numRoots, Quadratic &qRoots);
};
Quadratic operator+(const Quadratic &q1,const Quadratic &q2);
Quadratic operator*(double r, const Quadratic& q);
quadratic.cpp
#include<iostream>
#include "quadratic.h"
#include <cmath> // std::sqrt(double)
using namespace std;
//Default Constructor
Quadratic::Quadratic():a(0),b(0),c(0){}
//Had to add this to get the overloaded + operator to work
//(mainly because of the way I had it return the new instance)
Quadratic::Quadratic(float aSum, float bSum, float cSum)
{
this->a = aSum;
this->b = bSum;
this->c = cSum;
}
float Quadratic::get_a()
{
return a;
}
float Quadratic::get_b()
{
return b;
}
float Quadratic::get_c()
{
return c;
}
float Quadratic::evaluate(const float x)
{
return ((a*(x*x))+(b*x)+c);
}
void Quadratic::set()
{
float aNew=0.0,bNew=0.0,cNew=0.0;
cout<<"Enter a new a: ";
cin>>aNew;
cout<<"Enter a new b: ";
cin>>bNew;
cout<<"Enter a new c: ";
cin>>cNew;
this->b = bNew;
this->c = cNew;
this->a = aNew;
}
int Quadratic::numRoots(Quadratic &qTest)
{
float a= qTest.get_a();
float b= qTest.get_b();
float c= qTest.get_c();
int numRoots=0;
if ((a==0)&&(b==0)&&(c==0))
{
//every value of x = real root, so infinity
numRoots=3;
}
else if((a==0)&&(b==0)&&(c!=0))
{
numRoots=0;
}
else if((a==0)&&(b!=0))
{
numRoots=1;
//root is x= -c/b
}
else if((a!=0)&&( (b*b)<(4*a*c) ))
{
numRoots=0;
}
else if((a!=0)&&( (b*b)==(4*a*c) ))
{
numRoots=1;
//root is x= -b/2a
}
else if((a!=0)&&( (b*b)>(4*a*c) ))
{
numRoots=2;
//root is x= +/- quadratic formula
}
return numRoots;
}
float Quadratic::roots1(int numRoots, Quadratic &qRoots)
{
float root1=0.0;
float rootPlus=0.0;
float rootMinus=0.0;
if (numRoots==1)
{
if((a==0)&&(b!=0))
{
root1 = (((0-c)/b));// + ((0-c)%b));
}
if((a!=0)&&( (b*b)==(4*a*c) ))
{
root1 = (((0-b)/(2*a)));// + ((0-b)%(2*a)));
}
}
else if (numRoots == 2)
{
rootMinus= (((0-b)-sqrt((b*b)-(4*a*c)))/(2*a));
rootPlus= (((0-b)+sqrt((b*b)-(4*a*c)))/(2*a));
if (rootMinus > rootPlus) root1=rootPlus;
else root1=rootMinus;
}
else if (numRoots == 3) root1=0;
return root1;
}
float Quadratic::roots2(int numRoots, Quadratic &qRoots)
{
float root2=0.0;
float rootPlus=0.0;
float rootMinus=0.0;
if (numRoots==1)
{
if((a==0)&&(b!=0))
{
root2 = (((0-c)/b));// + ((0-c)%b));
}
if((a!=0)&&( (b*b)==(4*a*c) ))
{
root2 = (((0-b)/(2*a)));// + ((0-b)%(2*a)));
}
}
else if (numRoots == 2)
{
rootMinus= (((0-b)-sqrt((b*b)-(4*a*c)))/(2*a));
rootPlus= (((0-b)+sqrt((b*b)-(4*a*c)))/(2*a));
if (rootMinus < rootPlus) root2=rootPlus;
else root2=rootMinus;
}
else if (numRoots == 3) root2=0;
return root2;
}
Quadratic operator+(Quadratic &q1,Quadratic &q2)
{
float tempa,tempb,tempc=0.0;
tempa= q1.get_a() + q2.get_a();
tempb= q1.get_b() + q2.get_b();
tempc= q1.get_c() + q2.get_c();
Quadratic temp(tempa, tempb,tempc);
return temp;
// return Quadratic( q1.get_a() + q2.get_a(),
// q1.get_b() + q2.get_b(),
// q1.get_c() + q2.get_c());
}
Quadratic operator*(double r, Quadratic& q)
{
return Quadratic( q.get_a() * r,
q.get_b() * r,
q.get_c() * r);
}
main.cpp
#include<iostream>
//#include "quadratic.cpp""
#include "quadratic.h"
using namespace std;
int main()
{
//Default constructors called, all 3 coefficients set to 0
Quadratic q1;
Quadratic q2;
cout<<"Default constructor called\n"
<<"q1 a = "<<q1.get_a()<<"\n"
<<"q1 b = "<<q1.get_b()<<"\n"
<<"q1 c = "<<q1.get_c()<<"\n"
<<"q2 a = "<<q2.get_a()<<"\n"
<<"q2 b = "<<q2.get_b()<<"\n"
<<"q2 c = "<<q2.get_c()<<"\n";
//Call the set function to set all 3 coefficents of existing
//quadratic expression to new values
q1.set();
q2.set();
cout<<"\nSet function called. New values:\n"
<<"q1 a = "<<q1.get_a()<<"\n"
<<"q1 b = "<<q1.get_b()<<"\n"
<<"q1 c = "<<q1.get_c()<<"\n"
<<"q2 a = "<<q2.get_a()<<"\n"
<<"q2 b = "<<q2.get_b()<<"\n"
<<"q2 c = "<<q2.get_c()<<"\n";
//calls function to evaluate the quadratic expression for a given calue of x
cout<<"\nEnter x: ";
float x=0.0;
cin>>x;
cout<<"for q1, ax^2 + bx +c = "<<q1.evaluate(x)
<<"\nfor q2, ax^2 + bx +c = "<<q2.evaluate(x);
//add q1+q2 with overloaded + operator
Quadratic quad_sum = q1 + q2;
cout<<"\n\nAdding q1+_q2\n"
<<"\nq1_a + q2_a= "<<quad_sum.get_a()
<<"\nq1_b + q2_b= "<<quad_sum.get_b()<<" "
<<"\nq1_c + q2_c= "<<quad_sum.get_c();
//multiply the coefficients by r using overloaded * operator
cout<<"\n\nEnter a number to multiply the coefficeints by: ";
double r=0.0;
cin>>r;
Quadratic quad_prod=r*quad_sum;
cout<<"\nMultiplying q1 by r results in "
<<"\nnew a = "<<quad_prod.get_a()
<<"\nnew b = "<<quad_prod.get_b()
<<"\nnew c = "<<quad_prod.get_c();
//calculate number of and display roots
int numroots=q1.numRoots(q1);
cout<<"\n\nNumber of Roots for q1 = "<<numroots;
if (numroots != 0) cout<<"\nThey are: "<<q1.roots1(numroots, q1)<<" and "<<q1.roots2(numroots, q1);
}
Added
#ifndef QUAD_H_
#define QUAD_H_
and
#endif
to the header file, but still get "undefined reference" for every function call in the driver program.