Here is my code, for n and m, I consistently get 0 for n and nan for m, and I do not know why. I have tried everything I could, but n always shows 0 whilst m is always nan.
#include <iostream>
#include <iomanip>
#include <math.h>
#include <complex>
using namespace std;
int main()
{
float a, b, c, root1, root2, n, m ;
cout << "Please input values for a, b and c to represent the variables in equation : ax^2 + bx + c" << endl; // Dont know how to raise 2 instead of using ^2
cin >> a >> b >> c;
const float d = (b * b) - (4 * a * c);
cout << "Determinant is equal to " << d << endl;
cout << setprecision(3); // to set number of decimal places
n = b / 2 * a;
m = sqrt(d) / 2 * a;
if (d > 0) {
root1 = (-b + sqrt(d)) / (2.0 * a); // positive root
root2 = (-b - sqrt(d)) / (2.0 * a); // negative root
cout << "Determinant is greater than zero, therefore the equation has two real roots, which are " << root1 << " and " << root2 << endl;
}
else if (d < 0) {
cout << "Determinant is less than zero, therefore there would be two imaginary roots: " << n << " + " << m << "i ";
cout << "and " << n << " - " << m << "i" << endl;
}
}
you have to put parenthesis.
n = b / (2 * a);
m = sqrt(d) / (2 * a);
If the d is negative, you should first convert it to a non-negative number before feed it into sqrt(). Remember C/C++ does not equal to math language.
My quick fix:
#include <complex>
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
int main() {
float a, b, c, root1, root2, n, m;
cout << "Please input values for a, b and c to represent the variables in equation : ax^2 + bx + c " << endl; // Dont know how to raise 2 instead of using ^2
cin >> a >> b >> c;
const float d = (b * b) - (4 * a * c);
cout << "Determinant is equal to " << d << endl;
cout << setprecision(3); // to set number of decimal places
n = b / (2 * a);
if (d > 0) {
m = sqrt(d) / (2 * a);
root1 = (-b + sqrt(d)) / (2.0 * a); // positive root
root2 = (-b - sqrt(d)) / (2.0 * a); // negative root
cout << "Determinant is greater than zero, therefore the equation has two "
"real roots, which are "
<< root1 << " and " << root2 << endl;
} else if (d < 0) {
m = sqrt(-d) / (2 * a);
cout << "Determinant is less than zero, therefore there would be two "
"imaginary roots: "
<< n << " + " << m << "*i ";
cout << "and " << n << " - " << m << "*i" << endl;
}
}
A reference to sqrt() function:
http://www.cplusplus.com/reference/cmath/sqrt/
You will need to make some changes to get the correct answers for all cases First, you need to include the case of zero determinant which produces two identical real roots. You will need to calculate m with -d in the third case, and you have to make sure to change its sign into positive sign if necessary. For more aesthetic results, you can include special cases to omit n if it equals 0, and m if it equals 1.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a, b, c, root1, root2, n, m;
cout << "Please input values for a, b and c to represent the variables in equation : ax^2 + bx + c" << endl;
cin >> a >> b >> c;
const float d = b * b - 4 * a * c;
cout << "Determinant is equal to " << d << endl;
cout << setprecision(3); // to set number of decimal places
if (d > 0)
{
root1 = (-b + sqrt(d)) / 2 / a;
root2 = (-b - sqrt(d)) / 2 / a;
cout << "Determinant is greater than zero, therefore the equation has two real roots, which are " << root1 << " and " << root2 << endl;
}
else if (d == 0)
{
root1 = -b / 2 / a;
cout << "Determinant is zero, therefore the equation has two identical real roots, which both are " << root1 << endl;
}
else
{
n = -b / 2 / a;
m = sqrt(-d) / 2 / a;
if (m < 0)
m *= -1;
if (n == 0)
{
if (m == 1)
cout << "Determinant is less than zero, therefore there would be two imaginary roots: i and -i" << endl;
else
cout << "Determinant is less than zero, therefore there would be two imaginary roots: " << m << "i and -" << m << "i" << endl;
}
else
{
if (m == 1)
cout << "Determinant is less than zero, therefore there would be two imaginary roots: " << n << " + " << "i and " << n << " - " << "i" << endl;
else
cout << "Determinant is less than zero, therefore there would be two imaginary roots: " << n << " + " << m << "i and " << n << " - " << m << "i" << endl;
}
}
}
Related
I am trying to obtain the result of a quadratic equation with negative root, but the result that I obtain is not the same when I do the operation on paper, also the result is not the same only with negative roots when it is the opposite, it works perfectly.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int a, b, c;
double x1, x2;
cout << "Quadratic Formula" << endl;
cout << " -b + sqrt(b ^ 2) - 4ac" << endl;
cout << "x = -----------------------" << endl;
cout << " 2a" << endl;
cout << "" << endl;
cout << "a Value: " << endl;
cin >> a;
cout << "b Value: " << endl;
cin >> b;
cout << "c Value: " << endl;
cin >> c;
double sqRoot, det;
det = b * b - 4 * a * c;
if(det < 0)
{
sqRoot = sqrt(det * -1); //minus per minus = plus so it's possible to calculate the sqrt of
//the negative number
x1 = (-b + sqRoot)/ 2 * a;
x2 = (-b - sqRoot)/ 2 * a;
cout << "value of x1: " << x1 << " i"<< endl;
cout << "Value of x2: " << x2 << " i"<< endl;
}
else
{
sqRoot = sqrt(det);
x1 = (-b + sqRoot)/ 2 * a;
x2 = (-b - sqRoot)/ 2 * a;
cout << "Value of x1: " << x1 << endl;
cout << "Value of x2: " << x2 << endl;
}
}
You could use std::complex:
#include<iostream>
#include<cmath>
#include<complex>
using namespace std;
int main()
{
double a = 1.0;
double b = 4.0;
double c = 5.0;
double det = b * b - 4.0 * a * c;
auto sqRoot = sqrt(std::complex<double>(det));
auto x1 = (-b + sqRoot) / (2.0 * a);
auto x2 = (-b - sqRoot) / (2.0 * a);
cout << "value of x1: " << x1 << endl; // (-2,1)
cout << "value of x2: " << x2 << endl; // (-2,-1)
}
Your first problem is opeartion priority.
You should have a parenthesis in the following lines:
x1 = (-b + sqRoot)/ (2 * a);
x2 = (-b - sqRoot)/ (2 * a);
instead of
x1 = (-b + sqRoot)/ 2 * a;
x2 = (-b - sqRoot)/ 2 * a;
The second problem is your division using int variables.
The code shall be like the following:
#include<iostream>
#include<cmath>
#include <iomanip>
using namespace std;
int main()
{
int a, b, c;
double x1, x2;
cout << "Quadratic Formula" << endl;
cout << " -b + sqrt(b ^ 2) - 4ac" << endl;
cout << "x = -----------------------" << endl;
cout << " 2ac" << endl;
cout << "" << endl;
cout << "a Value: " << endl;
cin >> a;
cout << "b Value: " << endl;
cin >> b;
cout << "c Value: " << endl;
cin >> c;
double sqRoot, det;
det = b*b - 4*a*c;
// complex roots
if(det < 0)
{
sqRoot = sqrt(det *(-1)); //minus per minus = plus so it's possible to calculate the sqrt of
//the negative number
// HERE ALSO BUT SOLUTIONS ARE COMPLEX SO YOU NEED TO SHOW IMAGINARY PART AND REAL PART
// x1 = (-b + sqRoot)/ (2 * a); // ==>x=-b/(double)(2*a) and y =i*sqRoot/(double)(2*a)
// x2 = (-b - sqRoot)/ (2 * a);//==>x=-b/(double)(2*a) and y =-i*sqRoot/(double)(2*a)
cout << "value of x1: " << std::setprecision (4)<< (-b/(double)(2*a)) << "+"<<sqRoot/(2*a)<<*"i"<< endl;
cout << "Value of x2: " << std::setprecision (4)<< (-b/(double)(2*a)) << -sqRoot/(2*a)<<"i"<<endl;
}
else
{
sqRoot = sqrt(det);
// ALSO HERE
x1 = (-b + sqRoot)/ (2 * a);
x2 = (-b - sqRoot)/ (2 * a);
cout << "Value of x1: " << x1 << endl;
cout << "Value of x2: " << x2 << endl;
}
}
the results can be tested below:
3x^2 + 4x + 2 = 0
gives for the execution:
Quadratic Formula
-b + sqrt(b ^ 2) - 4ac
x = -----------------------
2ac
a Value:
3
b Value:
4
c Value:
2
value of x1: -0.6667+0.4714i
Value of x2: -0.6667-0.4714i
I am attempting to write a function that takes a value x and calculates the cos x by the series expansion, I'm always getting -inf, indifferent which value is read in.
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int fac(int n){
return n == 0 || n == 1 ? 1 : n * fac(n-1);
}
int main(){
double eps = 1e-15;
double x;
cin >> x;
long double ak = 1, sn = 0;
for(int k=1; abs(ak) > eps * abs(sn); k++){
double sgn = k % 2 == 0 ? 1 : -1;
sn += ak;
ak = sgn * pow(x, 2 * k) / fac(2*k);
}
cout << setprecision(4) << setw(5) << "x" << setprecision(15) << setw(20) << "cos x" << endl;
cout << setprecision(4) << setw(5)<< x << " " << setprecision(15) << setw(20) << sn << endl;
cout << setw(26) << cos(x) << endl;
return 0;
}
I debugged the code and at a certain point ak gets -inf. But why?
I get the following output:
This program is designed to aid in the analysis of triangles.
Would you like to specify the coordinates of a triangle (C),
or the lengths of their sides(S) ? Enter 'C' or 'S: s
Enter the length of side a: 3
Enter the length of side b: 4
Enter the length of side c: 5
The coordinates are A(0,0) , B(5,0) , C(nan,nan)
The angles are A = nan, B = nan and C = nan
The desired output is:
The coordinates of the triangle are at A(0,0), B(5,0) and C(3.2,2.4). The angles are A = 0.643501, B = 0.927295, and C = 1.5708
I've tried declaring variables in the beginning of main, as well as initializing them to 0. I either get a nan error or the incorrect values for my output
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double PI = 3.1415926535897932384626433832795;
int main() {
char mode = ' ';
cout << "\n\n";
cout << setw(10) << "" << "This program is designed to aid in the analysis of triangles. " << endl;
cout << setw(10) << "" << "Would you like to specify the coordinates of a triangle (C), " << endl;
cout << setw(10) << "" << "or the lengths of their sides(S) ? Enter 'C' or 'S: " ;
while (cin >> mode)
{
if (mode == 'C' || mode == 'c')
{
double Ax, Ay, Bx, By, Cx, Cy;
cout << "\n";
cout << setw(10) << "" << "Enter the x coordinate of point A: ";
cin >> Ax;
cout << setw(10) << "" << "Enter the y coordinate of point A: ";
cin >> Ay;
cout << setw(10) << "" << "Enter the x coordinate of point B: ";
cin >> Bx;
cout << setw(10) << "" << "Enter the y coordinate of point B: ";
cin >> By;
cout << setw(10) << "" << "Enter the x coordinate of point C: ";
cin >> Cx;
cout << setw(10) << "" << "Enter the y coordinate of point C: ";
cin >> Cy;
double a = sqrt((Cx - Bx) * (Cx - Bx) + (Cy - By) * (Cy - By));
double b = sqrt((Ax - Cx) * (Ax - Cx) + (Ay - Cy) * (Ay - Cy));
double c = sqrt((Ax - Bx) * (Ax - Bx) + (Ay - By) * (Ay - By));
double A = acos(((b * b) + (c * c) - (a * a)) / 2 * b * c);
double B = asin(b*sin(A) / a);
double C = asin(c*sin(A) / a);
cout << "\n" << setw(10) << "" << "The lengths of the sides are: a = " << a << ", b = " << b << " and c = " << c << endl;
cout << setw(10) << "" << "The angles are A = " << A << ", B = " << B << " and C = " << C << endl;
}
else if (mode == 'S' || mode == 's')
{
double a = 0, b = 0, c = 0;
cout << setw(10) << "" << "Enter the length of side a: ";
cin >> a;
cout << setw(10) << "" << "Enter the length of side b: ";
cin >> b;
cout << setw(10) << "" << "Enter the length of side c: ";
cin >> c;
if (a + b > c && b + c > a && a + c > b)
{
double A = acos(((b * b) + (c * c) - (a * a)) / 2 * b * c);
double B = asin(b*sin(A) / a);
double C = asin(c*sin(A) / a);
double Ax = 0;
double Ay = 0;
double Bx = c;
double By = 0;
double Cx = b * (cos(A) * PI / 180);
double Cy = b * (sin(A) * PI / 180);
cout << setw(10) << "" << "The coordinates are A(" << Ax << "," << Ay << ") , B(" << Bx << "," << By << ") , C(" << Cx << "," << Cy << ")" << endl;
cout << setw(10) << "" << "The angles are A = " << A << ", B = " << B << " and C = " << C << endl;
}
else
cout << setw(10) << "" << "These lengths don't form a triangle. Try again";
}
else
{
cout << setw(10) << "" << "Please enter 'S' or'C': ";
cin >> mode;
}
}
}
multiplication(*) and division(/) operators are having same precedence and associativity is left-to-right, just change the angle A calculation to
double A = acos(((b * b) + (c * c) - (a * a)) / (2 * b * c));
Using a Linear Congruent Generator I am able to create two independent Pseudo-Random number sequences which are uniformly distributed. I am trying to alter my program to allow it to use these sequences and perform a Box-Muller transform to change them into a normally distributed set.
The issue I am having however is that my new "normally distributed random number" (Z) is always equal to zero regardless of the input seed values for the two uniform sequences.
Any tips would be gratefully appreciated.
Many Thanks
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
#define M 4294967295
unsigned long get_rand(unsigned long x) //establishing function to generate random numbers
{
unsigned long a = 2269477;
unsigned long b = 1; //Values taken from wikipedia for Linear Congruence Method
unsigned long m = M;
unsigned long y;
y = (a * x + b) % m;
return y;
}
unsigned long get_normal(unsigned long x1, unsigned long x2)
{
unsigned long R;
unsigned long phi;
unsigned long u;
R = sqrt(-2 * log(x1)); //Box-Muller Transform
phi = (2 * M_PI*x2);
u = R*cos(phi);
return u;
}
double u1, u2, Z;
double bin0 = 0;
double bin1 = 0;
double bin2 = 0; //Variables used to store frequency of each number range
double bin3 = 0;
double bin4 = 0;
double bin5 = 0;
double bin6 = 0;
double bin7 = 0;
double bin8 = 0;
double bin9 = 0;
int main() {
double seed1,seed2;
cout << "Please enter seed values " << endl;
cin >> seed1;
cout << "\n";
cin >> seed2;
double x;
cout << "Please enter how many random numbers you want " << endl;
cin >> x;
cout << endl;
cout << "Random Numbers generated shown below: " << endl;
for (int i = 0; i < x; i++) //generate as many random numbers as the user has asked for
{
seed1 = get_rand(seed1);
seed2 = get_rand(seed2);
u1 = (double(seed1) / M); //changing to double and dividing by 'M' gets all values between 0 and 1
cout <<"U1 = " << u1 << endl; //type conversion to prevent integer rounding in division
u2 = (double(seed2) / M);
cout << "U2 = " << u2 << endl;
Z = get_normal(u1, u2);
cout <<"Z = " << Z << endl;
if (Z >= 0.0 && Z <= 0.1)
{ //checking for which intervals each random number falls into
bin0++; //if a number falls into this interval, increment the counter by 1 each time
}
else if (Z > 0.1 && Z <= 0.2) //if it doesnt fall into first interval, it will check the next interval, and so on...
{
bin1++;
}
else if (Z > 0.2 && Z <= 0.3)
{
bin2++;
}
else if (Z > 0.3 && Z <= 0.4)
{
bin3++;
}
else if (Z > 0.4 && Z <= 0.5)
{
bin4++;
}
else if (Z > 0.5 && Z <= 0.6)
{
bin5++;
}
else if (Z > 0.6 && Z <= 0.7)
{
bin6++;
}
else if (Z > 0.7 && Z <= 0.8)
{
bin7++;
}
else if (Z > 0.8 && Z <= 0.9)
{
bin8++;
}
else if (Z > 0.9 && Z <= 1.0)
{
bin9++;
}
}
double binTotal = bin0 + bin1 + bin2 + bin3 + bin4 + bin5 + bin6 + bin7 + bin8 + bin9;
cout << endl;
int bin0Percent = (bin0 / binTotal) * 100; //working out a percentage
cout << " Number of values in range 0.0-0.1: " << bin0 << endl; //output screen for each interval
cout << " Percentage of values in this interval: " << bin0Percent << "%" << endl;
cout << endl;
int bin1Percent = (bin1 / binTotal) * 100;
cout << " Number of values in range 0.1-0.2: " << bin1 << endl;
cout << " Percentage of values in this interval: " << bin1Percent << "%" << endl;
cout << endl;
int bin2Percent = (bin2 / binTotal) * 100;
cout << " Number of values in range 0.2-0.3: " << bin2 << endl;
cout << " Percentage of values in this interval: " << bin2Percent << "%" << endl;
cout << endl;
int bin3Percent = (bin3 / binTotal) * 100;
cout << " Number of values in range 0.3-0.4: " << bin3 << endl;
cout << " Percentage of values in this interval: " << bin3Percent << "%" << endl;
cout << endl;
int bin4Percent = (bin4 / binTotal) * 100;
cout << " Number of values in range 0.4-0.5: " << bin4 << endl;
cout << " Percentage of values in this interval: " << bin4Percent << "%" << endl;
cout << endl;
int bin5Percent = (bin5 / binTotal) * 100;
cout << " Number of values in range 0.5-0.6: " << bin5 << endl;
cout << " Percentage of values in this interval: " << bin5Percent << "%" << endl;
cout << endl;
int bin6Percent = (bin6 / binTotal) * 100;
cout << " Number of values in range 0.6-0.7: " << bin6 << endl;
cout << " Percentage of values in this interval: " << bin6Percent << "%" << endl;
cout << endl;
int bin7Percent = (bin7 / binTotal) * 100;
cout << " Number of values in range 0.7-0.8: " << bin7 << endl;
cout << " Percentage of values in this interval: " << bin7Percent << "%" << endl;
cout << endl;
int bin8Percent = (bin8 / binTotal) * 100;
cout << " Number of values in range 0.8-0.9: " << bin8 << endl;
cout << " Percentage of values in this interval: " << bin8Percent << "%" << endl;
cout << endl;
int bin9Percent = (bin9 / binTotal) * 100;
cout << " Number of values in range 0.9-1.0: " << bin9 << endl;
cout << " Percentage of values in this interval: " << bin9Percent << "%" << endl;
cout << endl;
}
get_normal returns a long, which cannot be between 0 and 1, since it is an integer. Storing the integer returned by the function into a double (Z) does not magically restore the discarded fractional part.
I think you should use floating point arithmetic (that is, doubles) in get_normal, and also change the return type.
By the way, the C++ standard library has lots of random number distributions. You might want to use it instead of trying to write your own.
M is too big, in the limit of a long. So any long divided (or modulus) by this M will result in 0. Perphaps you should use unsigned long long.
Also:
Instead of R = sqrt(-2 * log(x1)); try R= sqrt(fabs(2 * log(x1)));
Also
phi = (2 * M_PI*x2);
u = R*cos(phi);
phi is always an multiple of 2*PI, so cos(phi)= 1.
I'm having issues with the code below:
#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;
int main()
{
ifstream fin("input.txt");
ofstream fout("output.txt");
float discriminant, A, B, C, root1, root2;
fin >> A >> B >> C;
while (A != -99)
{
discriminant = (pow(B, 2.0) - 4 * A*C);
if (A == 0)
{
fout << A << "\t" << B << "\t" << C << "\t" << root1 << "\t" << root2 << endl;
}
else if (discriminant > 0)
{
root1 = (-B - sqrt(discriminant)) / (2.0*A);
root2 = (-B + sqrt(discriminant)) / (2.0*A);
fout << A << "\t" << B << "\t" << C << "\t" << root1 << "\t" << root2 << endl;
}
else if (discriminant == 0)
{
fout << A << "\t" << B << "\t" << C << "\t" << root1 << "\t" << root2 << endl;
}
else
{
fout << A << "\t" << B << "\t" << C << "\t" << root1 << "\t" << root2 << endl;
}
fin >> A >> B >> C;
}
fout.close();
ifstream fin2("output.txt");
fin2 >> A >> B >> C >> root1 >> root2;
while (!fin2.eof())
{
cout << A << "\t" << B << "\t" << C << "\t" << root1 << "\t" << root2 << endl;
fin2 >> A >> B >> C >> root1 >> root2;
}
cout << endl;
cout << "Coded by Paye W. Kialain" << "\t"<< endl;
system("pause");
return 0;
}
In the project description, I was told to create an input file containing a, b, and c, which I did. The format of the output is also correct. It is a table displaying the a, b and c values along with the 2 calculated roots. However, the calculations of the roots seem to be off. Are my if statements the issue?
The statements discriminant == 0 and A == 0 are dangerous comparisons because discriminant and A are floats. Floating-point calculations are often accompanied with floating-point errors (Think errors you get in mathematical approximations).
Consider this simple example of floating-point errors:
#include <iostream>
#include <string>
int main()
{
float a = 3.0;
float b = 10.0;
std::cout.precision(20);
std::cout << a/b << std::endl;
}
3.0/10.0, that's elementary math! You'd expect the result to be 0.3. However, as it turns out, the result is 0.30000001192092895508. If a and b were doubles, the result would be 0.2999999999999999889. This is because the way floating-point numbers are represented in binary does not allow for an accurate representation of 0.3. Now imagine what would have happened if I had code like if(a/b == 0.3). The condition will never be satisfied.
A solution to this problem is to introduce an epsilon value. This epsilon value basically serves as a value for error tolerance.
float a = 3.0;
float b = 10.0;
const float epsilon = 0.000001;
if(fabs(a/b - 0.3) < epsilon) {
std::cout << "a/b is equal to 0.3!" << std::endl;
}