How write a program which solving cubic equation on c++ ? - Вопросы по С+
  • Чаты 4chT.com в телеграмм
    Наши группы в телеграмм

Вопрос How write a program which solving cubic equation on c++ ?

Регистрация
6 Дек 2013
Сообщения
75
Репутация
0
Спасибо
0
Монет
0
To write a C++ program that solves a cubic equation, you'll need to implement an algorithm capable of finding the roots of the equation of the form:

\[ ax^3 + bx^2 + cx + d = 0 \]

A general solution to a cubic equation can be quite complex due to the various cases that need to be handled, such as real and complex roots. However, I will provide you with a simple example using Cardano's formula, which works well when the cubic equation has three real roots. This will require using complex numbers since intermediate steps may involve them even if the final roots are real.

Here's an example of how you could implement such a program:

```cpp #include
#include
#include

// Function to calculate the cubic roots
std::vector solveCubic(double a, double b, double c, double d) {
std::vector roots;
// Check for the special case where the leading coefficient is 0, which would actually make the equation quadratic
if (a == 0) {
// Handle as a quadratic equation or linear equation
// ...
return roots;
}

// Normalize coefficients
double inv_a = 1.0 / a;
b *= inv_a;
c *= inv_a;
d *= inv_a;

// Compute the intermediate values
double delta0 = c * c - 3 * b * d;
double delta1 = 2 * c * c * c - 9 * b * c * d + 27 * d * d;
std::complex C = std::pow((delta1 - std::sqrt(delta1 * delta1 - 4 * delta0 * delta0 * delta0)) / 2.0, 1.0 / 3.0);

std::complex xi = std::complex(-1, std::sqrt(3)) / 2.0; // Represents the complex number (cos(120°) + i*sin(120°))

// Compute the three roots
std::complex root1 = -1.0 / 3.0 * (b + C + delta0 / C);
std::complex root2 = -1.0 / 3.0 * (b + xi * C + delta0 / (xi * C));
std::complex root3 = -1.0 / 3.0 * (b + xi * xi * C + delta0 / (xi * xi * C));

roots.push_back(root1);
roots.push_back(root2);
roots.push_back(root3);

return roots;
}

int main() {
double a, b, c, d;
std::cout a >> b >> c >> d;

auto roots = solveCubic(a, b, c, d);

for (int i = 0; i < roots.size(); ++i) {
std::cout
 
Регистрация
30 Мар 2013
Сообщения
56
Репутация
0
Спасибо
0
Монет
0
Не писать на этом языке. 4 года учил, ничего не понял.
 
Сверху Снизу