O'Reilly logo

Functional Programming in C#: Classic Programming Techniques for Modern Projects by Oliver Sturm

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PRECOMPUTATION

Precomputation is a technique with which most programmers are familiar in one or another manifestation. For example, trigonometric calculations are very important for 3D animation. At the same time, they are comparatively expensive. As a result, a technique similar to this is often used:

tatic void ImperativePrecomputation( ) {

  double[] sines = new double[360];

  for (int i = 0; i < 360; i++) {

    sines[i] = Math.Sin(i);

  }

 

  // Now your algorithm is just going to look up the sine

  // values in 'sines' instead of having to calculate them.

}

There’s a clear separation here between the calculations that are performed first, and the actual algorithm that uses the results. In practice, a class is usually used to encapsulate the pre-computation and the algorithms that use the results in object oriented programming. Here is such a class that pre-computes trigonometric functions and uses the results to rotate (2-dimensional) points:

image

public class PointRotator {

  public PointRotator( ) {

    InitLookups( );

  }

 

  float[] sines, cosines;

 

  private void InitLookups( ) {

    sines = new float[360];

    cosines = new float[360];

    for (int i = 0; i < 360; i++) {

      sines[i] = (float) Math.Sin(ToRad(i));

      cosines[i] = (float) Math.Cos(ToRad(i));

    }

  }

 

  public PointF RotatePointWithLookups(PointF sourcePoint,

    double angle) {

    double polarLength ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required