Advertisement
cd62131

CubeEquation

Feb 27th, 2014
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define _USE_MATH_DEFINE
  4. #include <math.h>
  5. #include <float.h>
  6. typedef enum { REAL, IMAGE } complex_t;
  7. int main(void) {
  8.   double a, b, c, d, p, q, D, x1, x2, x3, y1, y2, y3, Im, u, v, d_u, d_v, phi;
  9.   complex_t kind;
  10.   printf("3次方程式(ax^3+bx^2+cx+d=0)の各係数:\n");
  11.   scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
  12.   if (a == 0.) exit(1);
  13.   printf("3次方程式 (%g x^3 %+g x^2 %+g x %+g = 0) の解は\n", a, b, c, d);
  14.   p = (3 * a * c - b * b) / (9 * a * a);
  15.   q = (2 * b * b * b - 9 * a * b * c + 27 * a * a * d) / (54 * a * a * a);
  16.   D = q * q + p * p * p;
  17.   if (fabs(D) <= DBL_MIN) {
  18.     if (fabs(q) <= DBL_MIN) y1 = y2 = y3 = 0;
  19.     else { y1 = 2 * pow(-q, 1.0 / 3.0); y2 = y3 = -y1 / 2; }
  20.     kind = REAL;
  21.   }
  22.   else if (D < 0) {
  23.     phi = acos(-q / pow(-p * p * p, 1.0 / 3.0));
  24.     y1 = 2 * sqrt(-p) * cos(phi / 3);
  25.     y2 = -2 * sqrt(-p) * cos(phi / 3 + M_PI / 3);
  26.     y3 = -2 * sqrt(-p) * cos(phi / 3 - M_PI / 3);
  27.     kind = REAL;
  28.   }
  29.   else {
  30.     d_u = -q + sqrt(D); d_v = -q - sqrt(D);
  31.     if (d_u >= 0) u = pow(d_u, 1.0 / 3.0); else u = -pow(-d_u, 1.0 / 3.0);
  32.     if (d_v >= 0) v = pow(d_v, 1.0 / 3.0); else v = -pow(-d_v, 1.0 / 3.0);
  33.     y1 = u + v; y2 = y3 = -y1 / 2; Im = sqrt(3) / 2 * (u - v); kind = IMAGE;
  34.   }
  35.   x1 = y1 - b / (3 * a); x2 = y2 - b / (3 * a); x3 = y3 - b / (3 * a);
  36.   if (kind == REAL) printf("x1 = %g, x2 = %g, x3 = %g\n", x1, x2, x3);
  37.   else printf("x1 = %g, x2 = %g + %g i, x3 = %g - %g i\n", x1, x2, Im, x3, Im);
  38.   return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement