#include #include #include #include /*************************************************** * Cubic Hermite approximation of sine * * We will approximate sin(x) on the interval * * 0 <= x <= pi/2 * * with a cubic polynomial. * * Rather than simply requiring the polynomial to * pass through two points, we also require its * derivative to agree with the derivative of sine * at those points: * * p(0) = 0 * p'(0) = 1 * * p(pi/2) = 1 * p'(pi/2) = 0. * * These are exactly the values and derivatives of * sin(x) at the two endpoints. * * A polynomial constructed by matching both values * and derivatives in this manner is called a * Hermite interpolating polynomial. * * * DEFAULT ARGUMENT * * By default, my_sin() assumes that its argument is * measured in radians: * * my_sin( 0.5 ) * * If the second argument is true, the argument is * instead interpreted as degrees: * * my_sin( 30.0, true ) * * The default argument must appear in the function * declaration so that the compiler knows what value * to supply when it encounters a function call with * only one argument. ***************************************************/ // Function declarations int main(); double my_sin( double const x, bool const using_degrees = false ); // Function definitions int main() { for ( int k{ 0 }; k <= 9; ++k ) { std::cout << "sin(" << 10*k << " deg) = " << my_sin( 10.0*k, true ) << std::endl; } std::cout << std::endl; // The default value of using_degrees is false, // so these arguments are interpreted as radians. for ( int k{ 0 }; k <= 15; ++k ) { std::cout << "sin(" << 0.1*k << ") = " << my_sin( 0.1*k ) << std::endl; } return 0; } /*************************************************** * my_sin * * Return a cubic Hermite approximation of sin(x) * for * * 0 <= x <= pi/2. * * If using_degrees is true, x is interpreted as * degrees and converted to radians. * * Notice that the default argument is not repeated * in the function definition. It appeared only in * the function declaration above. ***************************************************/ double my_sin( double const x, bool const using_degrees ) { double const pi{ std::numbers::pi }; double const radians_per_degree{ pi/180.0 }; double const radians{ using_degrees ? x*radians_per_degree : x }; assert( (radians >= 0.0) && (radians <= pi/2.0) ); return radians + 4.0*radians*radians/(pi*pi) *(radians - 4.0*radians/pi - pi + 3.0); }