OpenCores
URL https://opencores.org/ocsvn/tcp_socket/tcp_socket/trunk

Subversion Repositories tcp_socket

[/] [tcp_socket/] [trunk/] [chips2/] [docs/] [source/] [examples/] [example_2.rst] - Blame information for rev 4

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 4 jondawson
 
2
 
3
Approximating Sine and Cosine functions using Taylor Series
4
-----------------------------------------------------------
5
 
6
In this example, we calculate an approximation of the cosine functions using
7
the `Taylor series `_:
8
 
9
.. math::
10
 
11
    \cos (x) = \sum_{n=0}^{\infty} \frac{(-1)^n}{(2n)!} x^{2n}
12
 
13
 
14
The following example uses the Taylor Series approximation to generate the Sine
15
and Cosine functions. Successive terms of the taylor series are calculated
16
until successive approximations agree to within a small degree. A Sine
17
function is also synthesised using the identity :math:`sin(x) \equiv cos(x-\pi/2)`
18
 
19
.. code-block:: c
20
 
21
    /* taylor.c */
22
    /* Jonathan P Dawson */
23
    /* 2013-12-23 */
24
 
25
    /* globals */
26
    float pi=3.14159265359;
27
 
28
    /* approximate the cosine function using Taylor series */
29
 
30
    float taylor(float angle){
31
 
32
        float old, approximation, sign, power, fact;
33
        unsigned count, i;
34
 
35
        approximation = 1.0;
36
        old = 0.0;
37
        sign = -1.0;
38
        count = 1;
39
        power = 1.0;
40
        fact = 1.0;
41
 
42
        for(i=2; approximation!=old; i+=2){
43
            old = approximation;
44
 
45
            while(count<=i){
46
                power*=angle;
47
                fact*=count;
48
                count++;
49
            }
50
 
51
            approximation += sign*(power/fact);
52
            sign = -sign;
53
 
54
        }
55
        return approximation;
56
    }
57
 
58
    /* return the cosine of angle in radians */
59
 
60
    float cos(float angle){
61
        return taylor(angle);
62
    }
63
 
64
    /* return the sine of angle in radians */
65
 
66
    float sin(float angle){
67
        return cos(angle-(pi/2));
68
    }
69
 
70
 
71
    /* test routine */
72
 
73
    void main(){
74
        float x;
75
        float step=pi/25;
76
 
77
        for(x=-2*pi; x <= 2*pi; x += step){
78
           file_write(x, "x");
79
           file_write(cos(x), "cos_x");
80
           file_write(sin(x), "sin_x");
81
        }
82
    }
83
 
84
A simple test calculates Sine and Cosine for the range :math:`-2\pi <= x <= 2\pi`.
85
 
86
.. image:: images/example_2.png
87
 

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.