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

Subversion Repositories tcp_socket

[/] [tcp_socket/] [trunk/] [chips2/] [examples/] [example_1.py] - Blame information for rev 4

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 4 jondawson
#!/usr/bin/env python
2
 
3
import subprocess
4
import atexit
5
from math import pi
6
 
7
try:
8
    from matplotlib import pyplot
9
except ImportError:
10
    print "You need matplotlib to run this script!"
11
    exit(0)
12
 
13
children = []
14
def cleanup():
15
    for child in children:
16
        print "Terminating child process"
17
        child.terminate()
18
atexit.register(cleanup)
19
 
20
def run_c(file_name):
21
    process = subprocess.Popen(["../c2verilog", "iverilog", "run", str(file_name)])
22
    children.append(process)
23
    process.wait()
24
    children.remove(process)
25
 
26
def test():
27
    run_c("sqrt.c")
28
    x = [float(i) for i in open("x")]
29
    sqrt_x = [float(i) for i in open("sqrt_x")]
30
    pyplot.plot(x, sqrt_x)
31
    pyplot.xlim(0, 10.1)
32
    pyplot.title("Square Root of x")
33
    pyplot.xlabel("x")
34
    pyplot.ylabel("$\\sqrt{x}$")
35
    pyplot.savefig("../docs/source/examples/images/example_1.png")
36
    pyplot.show()
37
 
38
def indent(lines):
39
    return "\n    ".join(lines.splitlines())
40
 
41
def generate_docs():
42
 
43
    documentation = """
44
 
45
Calculate Square Root using Newton's Method
46
-------------------------------------------
47
 
48
In this example, we calculate the sqrt of a number using `Newton's method
49
<http://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number>`_.
50
The problem of finding the square root can be expressed as:
51
 
52
.. math::
53
 
54
     n = x^2
55
 
56
Which can be rearranged as:
57
 
58
.. math::
59
 
60
     f(x) = x^2 - n
61
 
62
Using Newton's method, we can find numerically the approximate point at which
63
:math:`f(x) = 0`. Repeated applications of the following expression yield
64
increasingly accurate approximations of the Square root:
65
 
66
.. math::
67
 
68
    f(x_k) = x_{k-1} - \\frac{{x_{k-1}}^2 - n}{2x_{k-1}}
69
 
70
Turning this into a practical solution, the following code calculates the square
71
root of a floating point number. An initial approximation is refined using
72
Newton's method until further refinements agree to within a small degree.
73
 
74
.. code-block:: c
75
 
76
    %s
77
 
78
Note that the code isn't entirely robust, and cannot handle special cases such
79
as Nans, infinities or negative numbers.  A simple test calculates
80
:math:`\\sqrt{x}` where :math:`-10 < x < 10`.
81
 
82
.. image:: images/example_1.png
83
 
84
"""%indent(open("sqrt.c").read())
85
 
86
    document = open("../docs/source/examples/example_1.rst", "w").write(documentation)
87
 
88
test()
89
generate_docs()

powered by: WebSVN 2.1.0

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