The Challenge

The challenge is optional, but is a fun program to write, so tackle it if you have time and the inclination.

Recall from Calculus 1 that the derivative of a function is the slope of the function, and that the derivative of the sin(theta) is the cos(theta).

Demonstrate this by generating one full cycle of sine and cosine curves, and add a column for the slope of the sine curve.

You can modify the sample sine/cosine program (below) to generate 500 points over one full cycle, and add a ‘derivative(sine)’ column. To do this, calculate the slope from the previous point to the current for the sine column. The result you get should be very close in value to the cosine column, so a sensible strategy would be to add yet one more column which is the difference between your derivative and the cosine; all points in this last column should be very close to zero. (Won’t be exactly zero…we’re slightly out of phase the way we’re calculating the slop here.)

Verify your results by checking the first few points by hand with a calculator, then by plotting the point with excel or matlab.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <iomanip>      // so we can format our output nicely
#include <cmath>        // trig functions are in cmath header file

                        // sin( ), cos( ), tan( ) give us sine, cosine and tangent of an angle
                        // asin( ), acos( ) give us the arc-sine and arc-cosine.
                        // C++'s trig functions work in radians, not degrees.

using namespace std;

const double PI=3.14159263;             // create a constant for PI
// or: 
//const double PI=acos(-1.0);           // acos( ) gives us the arc-cosine.  Q: Why does this give us PI?

int main(void)
{
    double angle=30.0;
    double angle_radians = angle * 2.0 * PI / 360.0;    // 2 PI radians in a full circle
    double my_cosine = cos(angle_radians);              // trig functions work in radians, not degrees
    double my_sine   = sin(angle_radians);

    cout << angle << "degrees equals "<< angle_radians << "radians"<<endl;
    cout << "cosine of " << angle_radians << " is " << my_cosine << endl;
    cout << "sine   of " << angle_radians << " is " << my_sine << endl;

            // now print out 24 sines and cosines (actually, 25 of 'em)

    cout << "i" << "\t" << "theta" << "\t" << "cosine" << "\t" << "sine" << endl;
    cout << setprecision(4);        // output with four decimal places.
    for (int i=0;i<=24; i++)
    {
        double theta;
        theta = 2.0*PI/24.0 * i;     // got partway around the circle each time through the loop

        cout << i << "\t" << theta << "\t" << cos(theta) << "\t" << sin(theta) << endl;
    }

    return 0;
}

Last edited on
Topic archived. No new replies allowed.