Adding sine

exercise No. 118

Implementing sin ( x ) .

Q:

We may implement sin ( x ) in a similar fashion to Equation 1, “Power series definition of f x = e x :

Equation 2. Power series definition of f x = sin ( x )
sin ( x ) = x - x 3 3 ! + x 5 5 ! - x 7 7 ! + ... = k = 0 ( -1 ) k x 2 k + 1 ( 2 k + 1 ) !

Extend Figure 297, “An implementation sketch for the exponential” by adding a second method double sin(double). Do not forget to add suitable Javadoc comments and watch the generated documentation.

Test your implementation by calculating the known values sin ( π 2 ) , sin ( π ) and sin ( 4 π ) using java.lang.Math.PI. Explain your results' accuracy for these arguments.

A:

Taking seven terms into account we have the following results:

sin(pi/2)=0.9999999999939768, difference=-6.023181953196399E-12
sin(pi)=-7.727858895155385E-7, difference=-7.727858895155385E-7
sin(4 * PI)=-9143.306026012957, difference=-9143.306026012957

As with the implementation of e x larger (positive or negative) argument values show growing differences. On the other hand the approximation is remarkably precise for smaller arguments. The reason again is the fact that our power series is just a polynomial approximation showing errors growing along with larger argument values:

Figure 299. Comparing sin(x) and its approximation.
sin ( x ) and p 9 x = x - x 3 3! + x 7 7! - x 9 9!
Comparing sin(x) and its approximation.

The approximation is very good for smaller values but diverges rapidly for 4 < x .

You may also view the implementation of double Math.sin(double) along with its Javadoc.