// ----------------------------------------------- // Solving a given quadratic euation // 2015 (c) Tomonori Kouya, All rights reserved. // To compile: icpc -w -fp-model precise quadratic_eq_dd.cc -I/usr/local/include/qd -L/usr/local/lib -lqd -o quadratic_eq_dd // ----------------------------------------------- #include #include #include #include #include #include "qd_real.h" using namespace std; // Print usage void usage(const char *prog_name) { cout << "[usage] " << prog_name << " [a] [b] [c]" << endl; } int main(int argc, char *argv[]) { // Coefficients of a quadratic equation dd_real a, b, c, d, a2; complex x[2], sqrt_d; if(argc <= 1) { usage(argv[0]); return EXIT_SUCCESS; } fpu_fix_start(NULL); // Set coefficients a = b = c = (dd_real)0.0; if(argc >= 2) { a = (dd_real)argv[1]; if(argc >= 3) b = (dd_real)argv[2]; if(argc >= 4) c = (dd_real)argv[3]; } // print the given equation cout << setprecision(30) << a << " * x^2 + (" << b << ") * x + (" << c << ") = 0 " << endl; // Calculate solutions with analytic formulas d = b * b - 4 * a * c; if(d >= 0.0) sqrt_d = sqrt(d); else sqrt_d = complex(0.0, sqrt(-d)); a2 = 2.0 * a; x[0] = (- b + sqrt_d) / a2; x[1] = (- b - sqrt_d) / a2; // Print solutions cout << "x[0] = " << setprecision(30) << x[0] << endl; cout << "x[1] = " << setprecision(30) << x[1] << endl; return EXIT_SUCCESS; }