Lego Mindstorms NXT

Computation of Trig Functions - Example


Click here to see how trig functions can be used.

If a high degree of accuracy is not required, and memory space is limited, then computation provides an alternative to table look up methods. The following example illustrates this approach for the cosine function.

Given a processor allowing 32 bit signed integer arithmetic, a fair approximation for cosine(x), scaled by a multiplier of 10000 is

10000 * cos(x) = 10000 - X^2 – (X^2 / 2) + (X^4 / 25864)
 

where x is angle in degrees and "^" means exponentiation. For example, a^4 = aaaa. (This formula is derived from the Taylor series for the cosine function.)

The above formula may be implemented by NXT-G arithmetic blocks as shown below

The above is done in the NXT-G programming environment.   Each arithmetic block may be thought of as its NXT-G counter part, placed sequentially on the sequence beam.

The table below shows the values calculated by the above formula versus the more accurate, Excel cosine function.

degrees

approximation formula

Excel function

% error

0

10000

10000

0

5

9963

9962

0

10

9850

9848

0

15

9664

9659

0

20

9406

9397

0

25

9078

9063

0

30

8681

8660

0

35

8221

8192

0

40

7698

7660

0

45

7121

7071

0

50

6491

6428

1

55

5816

5736

1

60

5101

5000

1

65

4353

4226

1

70

3578

3420

2

75

2786

2588

2

80

1983

1736

2

85

1181

872

3

90

386

0

4

Click here for Excel spreadsheet that computes the table above.

As you can see, the error tends to increase as we approach 90 degrees. However if our application involves only mid-range angles, then the above algorithm provides accuracy to about plus or minus 2%.


Address comments, suggestions or discussion to