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

Subversion Repositories tcp_socket

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

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 4 jondawson
 
2
 
3
Calculate Square Root using Newton's Method
4
-------------------------------------------
5
 
6
In this example, we calculate the sqrt of a number using `Newton's method
7
`_.
8
The problem of finding the square root can be expressed as:
9
 
10
.. math::
11
 
12
     n = x^2
13
 
14
Which can be rearranged as:
15
 
16
.. math::
17
 
18
     f(x) = x^2 - n
19
 
20
Using Newton's method, we can find numerically the approximate point at which
21
:math:`f(x) = 0`. Repeated applications of the following expression yield
22
increasingly accurate approximations of the Square root:
23
 
24
.. math::
25
 
26
    f(x_k) = x_{k-1} - \frac{{x_{k-1}}^2 - n}{2x_{k-1}}
27
 
28
Turning this into a practical solution, the following code calculates the square
29
root of a floating point number. An initial approximation is refined using
30
Newton's method until further refinements agree to within a small degree.
31
 
32
.. code-block:: c
33
 
34
    /* sqrt.c */
35
    /* Jonathan P Dawson */
36
    /* 2013-12-23 */
37
 
38
    /* find absolute value of a floating point number*/
39
 
40
    float fabs(float n){
41
        if (n < 0.0) {
42
            return - n;
43
        } else {
44
            return n;
45
        }
46
    }
47
 
48
    /* approximate sqrt using newton's method*/
49
 
50
    float sqrt(float n){
51
        float square, x, old;
52
        x = 10.0;
53
        old = 0.0;
54
        while(fabs(old - x) > 0.000001){
55
            old = x;
56
            x -= (x*x-n)/(2*x);
57
        }
58
        return x;
59
    }
60
 
61
    /* test sqrt function*/
62
 
63
    void main(){
64
        float x;
65
        for(x=0.0; x <= 10.0; x+= 0.1){
66
            file_write(x, "x");
67
            file_write(sqrt(x), "sqrt_x");
68
        }
69
    }
70
 
71
Note that the code isn't entirely robust, and cannot handle special cases such
72
as Nans, infinities or negative numbers.  A simple test calculates
73
:math:`\sqrt{x}` where :math:`-10 < x < 10`.
74
 
75
.. image:: images/example_1.png
76
 

powered by: WebSVN 2.1.0

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