Statistics
| Branch: | Tag: | Revision:

root / gnuradio-core / src / python / gnuradio / eng_notation.py @ 5d69a524

History | View | Annotate | Download (2.1 kB)

1
#
2
# Copyright 2003 Free Software Foundation, Inc.
3
# 
4
# This file is part of GNU Radio
5
# 
6
# GNU Radio is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2, or (at your option)
9
# any later version.
10
# 
11
# GNU Radio is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
# 
16
# You should have received a copy of the GNU General Public License
17
# along with GNU Radio; see the file COPYING.  If not, write to
18
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19
# Boston, MA 02111-1307, USA.
20
# 
21
22
scale_factor = {}
23
scale_factor['E'] = 1e18
24
scale_factor['P'] = 1e15
25
scale_factor['T'] = 1e12
26
scale_factor['G'] = 1e9
27
scale_factor['M'] = 1e6
28
scale_factor['k'] = 1e3
29
scale_factor['m'] = 1e-3
30
scale_factor['u'] = 1e-6
31
scale_factor['n'] = 1e-9
32
scale_factor['p'] = 1e-12
33
scale_factor['f'] = 1e-15
34
scale_factor['a'] = 1e-18
35
36
def num_to_str (n):
37
    '''Convert a number to a string in engineering notation.  E.g., 5e-9 -> 5n'''
38
    m = abs(n)
39
    if m >= 1e9:
40
        return "%gG" % (n * 1e-9)
41
    elif m >= 1e6:
42
        return "%gM" % (n * 1e-6)
43
    elif m >= 1e3:
44
        return "%gk" % (n * 1e-3)
45
    elif m >= 1:
46
        return "%g" % (n)
47
    elif m >= 1e-3:
48
        return "%gm" % (n * 1e3)
49
    elif m >= 1e-6:
50
        return "%gu" % (n * 1e6)        # where's that mu when you need it (unicode?)
51
    elif m >= 1e-9:
52
        return "%gn" % (n * 1e9)
53
    elif m >= 1e-12:
54
        return "%gp" % (n * 1e12)
55
    elif m >= 1e-15:
56
        return "%gf" % (n * 1e15)
57
    else:
58
        return "%g" % (n)
59
60
61
def str_to_num (value):
62
    '''Convert a string in engineering notation to a number.  E.g., '15m' -> 15e-3'''
63
    try:
64
        scale = 1.0
65
        suffix = value[-1]
66
        if scale_factor.has_key (suffix):
67
            return float (value[0:-1]) * scale_factor[suffix]
68
        return float (value)
69
    except:
70
        raise RuntimeError (
71
            "Invalid engineering notation value: %r" % (value,))