Appendix D. Computing Sine Using a Power Series

This program is designed to compute the sine function using a power series. A very limited floating-point format is used to demonstrate some of the problems that can occur when using floating point.

The program computes each term in the power series and displays the result. It continues computing terms until the last term is so small that it doesn’t contribute to the final result. For comparison purposes, the result of the library function sin is displayed as well as the computed sine.

The program is invoked by:

sine value

where value is an angle in radians. For example, to compute sin(0) we use the command:

% sine 0
x**1     0.000E+00
1!       1.000E+00
x**1/1! 0.000E+00
1 term computed
sin(0.000E+00)=
  0.000E+00
Actual sin(0)=0

And to compute sin(π) we use the command:

% sine 3.141 x**1 3.141E+00 1! 1.000E+00 x**1/1! 3.141E+00 total 3.141E+00 x**3 3.099E+01 3! 6.000E+00 x**3/3! 5.165E+00 total -2.024E+00 x**5 3.057E+02 5! 1.200E+02 x**5/5! 2.548E+00 total 5.239E-01 x**7 3.016E+03 7! 5.040E+03 x**7/7! 5.985E-01 total -7.457E-02 x**9 2.976E+04 9! 3.629E+05 x**9/9! 8.201E-02 total 7.438E-03 x**11 2.936E+05 11! 3.992E+07 x**11/11! 7.355E-03 total 8.300E-05 x**13 2.897E+06 13! 6.227E+09 x**13/13! 4.652E-04 total 5.482E-04 x**15 2.858E+07 15! 1.308E+12 x**15/15! 2.185E-05 total 5.263E-04 x**17 2.819E+08 17! 3.557E+14 x**17/17! 7.927E-07 total 5.271E-04 x**19 2.782E+09 19! 1.217E+17 x**19/19! 2.287E-08 total 5.271E-04 x**21 2.744E+10 21! 5.109E+19 x**21/21! ...

Get Practical C++ Programming, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.