#include #include #include // Function declarations int main(); double linear_root( double a, double b ); double quadratic_root_lesser( double a, double b, double c ); double quadratic_root_greater( double a, double b, double c ); double quadratic_extreme( double a, double b, double c ); // Function definitions int main() { std::cout << "Starting tests" << std::endl; assert( linear_root( 5.0, 2.0 ) == -0.4 ); assert( linear_root( -0.4, 1.7 ) == 4.25 ); assert( linear_root( -0.683, 0.0 ) == 0.0 ); assert( linear_root( 0.2, -7.2 ) == 36.0 ); std::cout << linear_root( 0.0, 9.6 ) << std::endl; std::cout << "Finishing tests" << std::endl; return 0; } // double linear_root( ... ) // // @author Douglas Wilhelm Harder // @date 2020-09-09 // @version 1.0 // // @param a the linear coefficient 'a' of the // polynomial ax + b // @param b the constant coefficient 'b' of the // polynomial ax + b // // @returns the root of the polynomial ax + b // - If a == 0.0, return NaN. // // @algorithm // Equate the polynomial to zero: // // ax + b = 0. // // Solving for x gives // // x = -b/a. // // If a == 0.0, the polynomial is constant and there is // no unique root. In this case, return NaN. // // Exercises: // 1. What would happen if we did not check whether // a == 0.0 before calculating -b/a? // // Why is NaN a reasonable value to return when // a == 0.0? // // 2. Author the function // // double quadratic_extreme( // double a, double b, double c // ); // // that calculates the x-coordinate of the extreme // point (the maximum or minimum) of the quadratic // polynomial // // 2 // ax + bx + c. // // If a == 0.0, the polynomial is not quadratic and // has no unique extreme point. Return NaN. // // 3. Author the two functions // // double quadratic_root_lesser( // double a, double b, double c // ); // // double quadratic_root_greater( // double a, double b, double c // ); // // that calculate the real roots of the polynomial // // 2 // ax + bx + c. // // If the polynomial has two real roots, then // // quadratic_root_lesser( a, b, c ) // <= // quadratic_root_greater( a, b, c ). // // These two values are equal if and only if the // quadratic polynomial has a double root. // // If // // 2 // b - 4ac < 0, // // the polynomial has no real roots. Both functions // should return NaN. // // If a == 0.0, both functions should return the // root of the linear polynomial // // bx + c. // // You can call linear_root( b, c ) to calculate // this root. Consequently, if both a == 0.0 and // b == 0.0, both functions will return NaN. // // You will need to use std::sqrt(), which is // declared in the library. double linear_root( double a, double b ) { if ( a == 0.0 ) { return std::numeric_limits::quiet_NaN(); } return -b/a; }