Strange things happen

exercise No. 110

Summing up in a different order. Create comment in forum

Q:

We may reorder summing up within our power series defining sin ( x ) :

Equation 3. Reordering of terms with respect to an implementation.
sin ( x ) = x + ( - x 3 3 ! + x 5 5 ! ) + ( - x 7 7 ! + x 9 9 ! ) + ...

From a mathematical point of view there is no difference to Equation 2, “Power series definition of f x = sin ( x ) . Nevertheless:

  • Rename your current sine implementation to double sinOld(double).

  • Implement a new method double sin(double) using the above summing reordering.

Compare the results of double sinOld(double) and double sin(double) for seven terms. What do you observe? Do you have an explanation?

A:

The following results result from this test:

Old Implementation:+++++++++++++++++++++++++++++++++++++++

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

New reorder Implementation:+++++++++++++++++++++++++++++++++++++

sin(pi/2)=1.0000000000000435, difference=4.3520742565306136E-14
sin(pi)=2.2419510618081458E-8, difference=2.2419510618081458E-8
sin(4 * PI)=4518.2187229323445, difference=4518.2187229323445

Comparing corresponding values our reordered implementation is more than 100 times more precise. For larger values we still have a factor of two.

This is due to limited arithmetic precision: Each double value can only be approximated by an in memory representation of eight bytes. Consider the following example:

double one = 1.,
       a = 0.000000000000200,
       b = 0.000000000000201;

System.out.println("(1 + (a - b)) - 1:" + ((one + (a - b)) - one));
System.out.println("((1 + a) - b) - 1:" + (((one + a) - b) -  one));

This produces the following output:

(1 + (a - b)) - 1:-9.992007221626409E-16
((1 + a) - b) - 1:-8.881784197001252E-16

Errors like this sum up in a power series giving rise to reasonable deviations especially if higher powers are involved.