Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/mathlib.py
blob: c2e1ade28946f83854e52748e6e0fd7c1de22616 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# MathLib.py, generic math library wrapper by Reinier Heeres <reinier@heeres.eu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# Change log:
#    2007-07-03: rwh, first version

import types
import math
from decimal import Decimal

import logging
_logger = logging.getLogger('calc-activity')


class MathLib:
    ANGLE_DEG = math.pi/180
    ANGLE_RAD = 1
    ANGLE_GRAD = 1

    def __init__(self):
        self.constants = {}
        self.set_angle_type(self.ANGLE_DEG)
        self.set_constant('true', True)
        self.set_constant('false', False)
        self.set_constant('pi', self.parse_number('3.14'))
        self.set_constant('kb', self.parse_number('0'))
        self.set_constant('Na', self.parse_number('6.02214e23'))
        self.set_constant('e', self.exp(1))
        self.set_constant('c', self.parse_number('3e8'))
        self.set_constant('c_e', self.parse_number('0'))        #electron properties
        self.set_constant('m_e', self.parse_number('0'))
        self.set_constant('c_p', self.parse_number('0'))        #proton properties
        self.set_constant('m_p', self.parse_number('0'))
        self.set_constant('c_n', self.parse_number('0'))        #neutron properties
        self.set_constant('m_n', self.parse_number('0'))

    def set_angle_type(self, type):
        self.angle_scaling = self.d(type)
        _logger.debug('Angle type set to:%s',self.angle_scaling)

    def set_constant(self, name, val):
        self.constants[name] = val

    def get_constant(self, name):
        if name in  self.constants:
            return self.constants[name]
        else:
            return None

    def d(self, val):
        s = '%.10e' % val
        d = Decimal(s)
        return d.normalize()

    def parse_number(self, s):
        return Decimal(s)

    def format_number(self, n):
        if type(n) is types.BooleanType:
            if n:
                return 'True'
            else:
                return 'False'
        elif type(n) is types.NoneType:
            return 'Error'
        elif not isinstance(n, Decimal):
            return 'Error (no Decimal object)'
        (sign, digits, exp) = n.as_tuple()
        if len(digits) > 9:
            exp += len(digits) - 9
            digits = digits[:9]
        
        if sign:
            res = "-"
        else:
            res = ""
        int_len = len(digits) + exp
        
        if int_len == 0:
            if exp < -5:
                disp_exp = exp +len(digits) 
            else:
                disp_exp = 0
        elif 0 < int_len < 6:
            disp_exp = 0
        else:
            disp_exp = int_len - 1
        
        dot_pos = int_len - disp_exp
        for i in xrange(len(digits)):
            if i == dot_pos:
                if i == 0:
                    res += '0.'
                else:
                    res += '.'
            res += str(digits[i])

        if len(digits) < dot_pos:
            for i in xrange(len(digits), dot_pos):
                res += '0'

        if disp_exp != 0:
            res = res + 'e%d' % disp_exp

        print 'fn: %r into %r' % (n, res)
        return res

    def is_int(self, n):
        (sign, d, e) = n.normalize().as_tuple()
        return e == 0

    def is_float(self, n):
        if isinstance(n, Decimal):
            return not self.is_int(n)
        else:
            return False

    def is_bool(self, n):
        return type(n) is types.BoolType

    def compare(self, x, y):
        return x == y

    def negate(self, x):
        return -x

    def abs(self, x):
        return self.d(math.fabs(x))

    def add(self, x, y):
        return x + y

    def sub(self, x, y):
        return x - y

    def mul(self, x, y):
        return x * y

    def div(self, x, y):
        if y == 0:
            return None
        else:
            return x / y

    def pow(self, x, y):
        if self.is_int(y):
            return x ** y
        else:
            return self.d(math.pow(x, y))

    def sqrt(self, x):
        return self.d(math.sqrt(x))

    def mod(self, x, y):
        if self.is_int(y):
            return x % y
        else:
            return self.d(0)

    def exp(self, x):
        return self.d(math.exp(x))

    def ln(self, x):
        if x > 0:
            return self.d(math.log(x))
        else:
            return 0

    def log10(self, x):
        if x > 0:
           return self.d(math.log10(x))
        else:
            return 0

    def factorial(self, n):
        if not self.is_int(n):
            return self.d(0)

        res = n
        while n > 2:
            res *= n - 1
            n -= 1
        return res

    def sin(self, x):
        return self.d(math.sin(x * self.angle_scaling))

    def cos(self, x):
        _logger.debug('cos: x=%s, angle_scaling=%s', x, self.angle_scaling)
        return self.d(math.cos(x * self.angle_scaling))

    def tan(self, x):
        return self.d(math.tan(x * self.angle_scaling))

    def asin(self, x):
        return self.d(math.asin(x)) / self.angle_scaling

    def acos(self, x):
        return self.d(math.acos(x)) / self.angle_scaling

    def atan(self, x):
        return self.d(math.atan(x)) / self.angle_scaling

    def sinh(self, x):
        return self.d(math.sinh(x))

    def cosh(self, x):
        return self.d(math.cosh(x))

    def tanh(self, x):
        return self.d(math.tanh(x))

    def asinh(self, x):
        return self.d(math.asinh(x))

    def acosh(self, x):
        return self.d(math.acosh(x))

    def atanh(self, x):
        return self.d(math.atanh(x))

    def round(self, x):
        return self.d(round(x))

    def floor(self, x):
        return self.d(math.floor(x))

    def ceil(self, x):
        return self.d(math.ceil(x))