cardano's method in c++ [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i am trying to make a program that will compute for the root of a cubic function using cardano's method
here's my code:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a, b, c, d, value;
double f, g, h;
double i, j, k, l, m, n, p, po;
double r, s, t, u;
double x1, x2, x2re, x2im, x3re, x3im, x3;
cin >> value;
for(int w=1; w <= value; w++){
cin >> a >> b >> c >> d;
cout << "CUBIC EQUATION : " << a << " x^3 + " << b << " x^2 + " << c <<" x + " << d << " = 0" << endl;
f = ((3*c/a)-((b*b)/(a*a)))/3;
g = ((2*(b*b*b)/(a*a*a))-(9*b*c/(a*a))+(27*d/a))/27;
h = ((g*g)/4)+((f*f*f)/27);
if(f==0 && g==0 && h==0){ // all roots are real and equal
x1 = pow((d/a),0.33333333333333333333333333333333);
x2 = pow((d/a),0.33333333333333333333333333333333);
x3 = pow((d/a),0.33333333333333333333333333333333);
cout << "x = " << x1 << endl;
cout << "x = " << x2 << endl;
cout << "x = " << x3 << endl;
}
else if(h<=0){ // all 3 roots are real
i = pow((((g*g)/4)-h),0.5);
j = pow(i,0.33333333333333333333333333333333);
k = acos((g/(2*i))*-1);
l = j * -1;
m = cos(k/3);
n = sqrt(3) * sin(k/3);
p = (b/(3*a))*-1;
x1 = (2*j)*m-(b/(3*a));
cout << "x = " << x1 << endl;
x2 = l * (m+n) + p;
cout << "x = " << x2 << endl;
x3 = l * (m-n) + p;
cout << "x = " << x3 << endl;
}
else if(h>0){
r = ((g/2)*-1)+pow(h,0.5);
s = pow(r,0.33333333333333333333333333333333);
t = ((g/2)*-1)-pow(h,0.5);
u = pow((t),0.33333333333333333333333333333333);
x1 = (s+u) - (b/(3*a));
cout << "x = " << x1 << endl;
x2re = (((s+u)*-1)/2) - (b/(3*a));
x2im = -(s-u)*pow(3,0.5)/2;
cout << "x = (" << x2re << "," << x2im << ")" << endl;
x3re = (((s+u)*-1)/2) - (b/(3*a));
x3im = (s-u)*pow(3,0.5)/2;
cout << "x = (" << x3re << "," << x3im << ")" << endl;
}
}
return 0;
}
can anyone help implement a user-defined ComplexNumber in this code?
I want to use this link http://en.wikipedia.org/wiki/Cubic_function but i cant understand this.

can anyone help implement a user-defined ComplexNumber in this code?
Don't implement a user-defined ComplexNumber type. Use the one provided by the language. Just #include <complex>. With that you can have a complex variable simply by complex<double> variable_name.
Code comments:
It's better to use std::sqrt(x) rather than std::pow(x, 0.5).
If you are on a POSIX-compliant machine, your math library has a cube root function, cbrt(double) in the header . (It may not be exported to the C++ header .) This too is preferable over std::pow(x,0.33333333333333333333333333333333).

Related

Wrong root from quadratic equation calculator

I was wondering if someone could help me in this problem.
So i tested the code but it didn't show the right answer below for
equation result of x2 + 5x + 6
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
double roots() {
double a, b, c, x1, x2;
cout << "Enter quadratic equation in order (a, b, c): \n";
cin >> a >> b >> c;
double discriminant = b * b - 4 * a * c;
x1 = -b + sqrt(discriminant) / 2 * a;
x2 = -b - sqrt(discriminant) / 2 * a;
if (discriminant >= 0 && a > 1) {
cout << "Your quadratic equation is " << a << "x^2 + " << b << " x + " << c << '\n';
cout << "x1 = " << x1 << '\n';
cout << "x2 = " << x2 << '\n';
}
else if (a == 1) {
cout << "Your quadratic equation is " << "x^2 + " << b << " x + " << c << '\n';
cout << "x1 = " << x1 << '\n';
cout << "x2 = " << x2 << '\n';
}
else {
cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}
You have the formula incorrect. Try this
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);
Notice the extra parenthesis in order to put 2*a in the denominator and have it divide both b and the sqrt().
You also need to check if discriminant >= 0 before doing so, because if it is negative there is no root and the above lines are going to fail.
Firstly, using namespace std was not used, so if you don't want to use it write std::court and std::cin. Secondly, the formula is b^2 -4ac so you need to put round brackets around b*b so that the answer is subtracted from -4ac. Then, you don't need to write else if for a==1 you can add it in the above condition as a>=1 and else put down a condition where discriminant is >=0 but a==0 which violates quadratic eq condition and you can write a cannot be equal to zero. Also, the main formula for x1 and x2 is wrong since the bracket should be applied around -b+sqroot(discriminant) so that the answer is then divided by multiplication of (2*a). Otherwise, what happens is that first sqrt is divided by 2 then multiplied by a and then added to -b.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
double roots() {
double a, b, c, x1, x2;
std::cout << "Enter quadratic equation in order (a, b, c): \n";
std::cin >> a >> b >> c;
double discriminant = (b * b)- (4 * a * c);
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant))/ (2 * a);
if (discriminant >= 0 && a >= 1) {
std::cout << "Your quadratic equation is " << a << "x^2 + " << b << " x
+ " << c << '\n';
std::cout << "x1 = " << x1 << '\n';
std::cout << "x2 = " << x2 << '\n';
}
else if (a==0){
std::cout << "a cannot be zero!";
exit(1);
}
else{
std::cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}

Pointer/Array Indexing Returning Unexpected Values

I am implementing code for convolution in C++ (I know it exists already but I'm just doing it for practice since I'm a beginner), and while I can get the correct output, there are certain methods I'm trying that are giving unexpected output depending on how I access the values of the convolution that I store in an array and I'm not sure why.
The function code that works, whether I access the values by array indexing or with pointer incrementing, is:
void conv(int M, int* h, int L, int* x, int* y) {
int n, m = 0;
for (n = 0; n < L + M - 1; n++) {
for (m = std::max(0, n - L + 1); m <= std::min(n, M - 1); m++) {
*(y+n) += *(h + m) * *(x + n - m);
};
std::cout << "using array index: " << std::endl;
std::cout << "n = " << n << " " << "y = " << y[n] << " " << std::endl;
std::cout << std::endl;
std::cout << "using pointer: " << std::endl;
std::cout << "n = " << n << " " << "y = " << *(y+n) << " " << std::endl;
std::cout << std::endl;
//y++;
}
}
However, if I make slight changes to this (numbered below):
void conv(int M, int* h, int L, int* x, int* y) {
int n, m = 0;
for (n = 0; n < L + M - 1; n++) {
for (m = std::max(0, n - L + 1); m <= std::min(n, M - 1); m++) {
*y += *(h + m) * *(x + n - m); //[1]
};
std::cout << "using array index: " << std::endl;
std::cout << "n = " << n << " " << "y = " << y[n] << " " << std::endl;
std::cout << std::endl;
std::cout << "using pointer: " << std::endl;
std::cout << "n = " << n << " " << "y = " << *y << " " << std::endl; //[2]
std::cout << std::endl;
y++; //[3]
}
}
In this case, only accessing the values via pointer provides the correct output, while accessing it via array indexing provides random garbage.
My test code is:
int main()
{
const int M = 5; const int L = 6;
int y[M + L - 1] = {};
int x[L] = { 1, -2, 5, 3, 8, -4 };
int h[M] = { 1,2,3,4,5 };
int* yPtr = y; int* hPtr = h; int* xPtr = x;
conv(M, hPtr, L, xPtr, yPtr);
std::cout << "value after leaving conv" << std::endl;
for (int i = 0; i < M+L-1; i++) {
std::cout << "i = " << i << " " << "y = " << y[i] << std::endl;
}
}
which always provides the correct output even when accessing the array elements in the for loop of the conv provides the incorrect output.
For reference, the correct output is y = {1, 0, 4, 11, 26, 31, 53, 35, 24, -20}.
What am I doing wrong in the second example of conv to be getting the wrong values when using array indexing?
In the second version of the code, you are incrementing y as you go through the loop, so y[n] in the second version is equivalent to y[2*n] in the first. Once n reaches half the size of the array, y[n] is past the end of the array, thus garbage. *y is equivalent to y[0].
Your example is sufficiently weird to be a little difficult to read, but from your second version, this is fishy:
std::cout << "n = " << n << " " << "y = " << y[n] << " " << std::endl;
You're incrementing y as you go, so y[n] is going to go to weird places fast.
I saved Y as int * yOrig = y; and then used that, and I think I'm getting the output you expect, but I'm not sure.

Creating a C++ program to solve an equation of motion using Euler's method

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/

C++ 2D array table

I'm trying to create an 2D array table in C++ with a for loop and this is my code below.
//receive user input
double nSideA = sSideA;
for( double x = nSideA; x < eSideA; x = x + incrementA){
cout << "a=" << fixed << setprecision(1) << setw(4) << nSideA << " ";
nSideA += incrementA;
} // table header
cout << "\n"; //spacing
for (double y = sSideB; y < eSideB; y = y + incrementB){
for( double x = sSideA; x < eSideA; x = x + incrementA){
sSideA += incrementA;
sSideB += incrementB;
hypo = sqrt( pow(sSideA,2) + pow(sSideB,2) );
cout << "b=" << fixed << setprecision(1) << setw(4) << sSideB << " ";
cout << fixed << setprecision(3) << setw(3) << hypo << " " << endl;
}} // content
My output for the table is something like :
b= 2.0 2.828
b= 3.0 4.243
b= 4.0 5.657
b= 5.0 7.071
b= 6.0 8.485
b= 7.0 9.899
with b not looping properly. (Printed all in a column thanks to Frax in the comments with endl;)
This is supposed to be a program that performs the Pythagoras Theorem. I intend for my output to be like
However, the results go wrong on the second loop where a[1][1] ends up at a[1][0] , a[2][2] ends up at a[2][0] and so on.
How do I fix my for loop to make it print a proper table?
Thank you.

Don't print variable if it's zero

double a, b, c, d, x, y;
char operation
cout << setw(6) << a << b
<< setw(3) << operation
<< setw(6) << c << d
<< " = "
<< setw(6) << x << y
<< endl;
I'm making a calculator which takes two complex numbers and adds subtracts etc. My question is how do I format my output so that 0's are not displayed.
I.E. if the input is (a+bi)(c+di) the output is a+bi * c+di = x+yi But a, b, c, d, x, y are only displayed if they are nonzero.
I know I can do it with if statements and stuff but I was hoping there's a shorter, more efficient, path.
I don't think you can avoid doing the condition and printing if non-zero somewhere.
About all you can do is wrap it up so most code doesn't need to deal with it:
class complex {
double x;
double i;
public:
// ...
friend std::ostream &operator<<(std::ostream &os, complex const &c) {
// if both parts are 0, we probably want to print *something*
if (c.x == 0.0 && c.i == 0.0)
return os << 0;
if (c.x != 0.0)
os << c.x;
if (c.i != 0.0)
os << c.i << "i";
return os;
}
};
complex a, b, c;
// ...
cout << a << operation << b << " = " c << "\n";
You'll have to add a little more if you want this to honor (for example) width/precision correctly (though for real use, you undoubtedly want to use the complex class that's already in the standard library instead).
Yes, you can do it by including <complex>
std::complex<double> com_one; // value 0 + 0i
std::complex<double> com_two(3.14); // value 3.14 + 0i
std::complex<double> com_three(1.5, 3.14) // value 1.5 + 3.14i
std::complex<double> com_four(com_two); // value is also 3.14 + 0i
Then to use arithmetic operations, you can just use
std::cout << com_one + com_two << std::endl;
std::cout << com_one - 3.14 << std::endl;
std::cout << 2.75 * com_two << std::endl;
com_one += com_three / 2.0;
Source: http://stdcxx.apache.org/doc/stdlibug/20-2.html
For checking if it's a zero check it using if, and compare it with a zero. This is the most clean technique.