unit_math.py 2.23 KB
Newer Older
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
#!/bin/env python
"""
Module simtk.unit.math

Arithmetic methods on Quantities and Units
"""

__author__ = "Christopher M. Bruns"
__version__ = "0.5"


import math
from quantity import is_quantity
from unit_definitions import *

####################
### TRIGONOMETRY ###
####################

def sin(angle):
    """
    Examples
    
    >>> sin(90*degrees)
    1.0
    """
    if is_quantity(angle):
        return math.sin(angle/radians)
    else:
        return math.sin(angle)

def sinh(angle):
    if is_quantity(angle):
        return math.sinh(angle/radians)
    else:
        return math.sinh(angle)

def cos(angle):
    """
    Examples
    
    >>> cos(180*degrees)
    -1.0
    """
    if is_quantity(angle):
        return math.cos(angle/radians)
    else:
        return math.cos(angle)

def cosh(angle):
    if is_quantity(angle):
        return math.cosh(angle/radians)
    else:
        return math.cosh(angle)

def tan(angle):
    if is_quantity(angle):
        return math.tan(angle/radians)
    else:
        return math.tan(angle)

def tanh(angle):
    if is_quantity(angle):
        return math.tanh(angle/radians)
    else:
        return math.tanh(angle)

def acos(x):
    """
    >>> acos(1.0)
    Quantity(value=0.0, unit=radian)
    >>> print acos(1.0)
    0.0 rad
    """
    return math.acos(x) * radians
    
def acosh(x):
    return math.acosh(x) * radians
    
def asin(x):
    return math.asin(x) * radians

def asinh(x):
    return math.asinh(x) * radians

def atan(x):
    return math.atan(x) * radians
    
def atanh(x):
    return math.atanh(x) * radians
    
def atan2(x, y):
    return math.atan2(x, y) * radians

###################
### SQUARE ROOT ###
###################

def sqrt(val):
    """
    >>> sqrt(9.0)
    3.0
    >>> print sqrt(meter*meter)
    meter
    >>> sqrt(9.0*meter*meter)
    Quantity(value=3.0, unit=meter)
    >>> sqrt(9.0*meter*meter*meter)
    Traceback (most recent call last):
    ...
    ArithmeticError: Exponents in Unit.sqrt() must be even.
    """
    try:
        return val.sqrt()
    except AttributeError:
        return math.sqrt(val)

# run module directly for testing
if __name__=='__main__':
    # Test the examples in the docstrings
    import doctest, sys
    doctest.testmod(sys.modules[__name__])