1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 """convert to and from fractions
23 """
24
25 __version__ = "$Rev: 7036 $"
26
28 """
29 Converts a value to a fraction
30
31 @param value: the value to convert to a tuple
32 @type value: one of
33 - string, unicode
34 - number, eg int/float/long
35 - two sized tuple
36
37 @returns: the fraction
38 @rtype: a two sized tuple with 2 integers
39 """
40 def _frac(num, denom=1):
41 return int(num), int(denom)
42
43 if isinstance(value, basestring):
44 noSlashes = value.count('/')
45 if noSlashes == 0:
46 parts = [value]
47 elif noSlashes == 1:
48 parts = value.split('/')
49 else:
50 raise ValueError('Expected at most one /, not %r' % (value,))
51 return _frac(*parts)
52 elif isinstance(value, tuple):
53 if len(value) != 2:
54 raise ValueError(
55 "Can only convert two sized tuple to fraction")
56 return value
57 elif isinstance(value, (float, int, long)):
58 return _frac(value)
59 else:
60 raise ValueError(
61 "Cannot convert %r of type %s to a fraction" % (
62 value, type(value).__name__))
63
65 """
66 Converts a fraction to a float
67 @param value: the value to convert to a tuple, can be one of:
68 @type value: a two sized tuple with 2 integers
69 @returns: fraction representation in float
70 @rtype: float
71 """
72 assert type(value) in [list, tuple], value
73 assert len(value) == 2, value
74 return float(value[0]) / float(value[1])
75
77 """
78 Converts a fraction to a string
79 @param value: the value to convert to a tuple, can be one of:
80 @type value: a two sized tuple with 2 integers
81 @returns: fraction representation as a string
82 @rtype: string
83 """
84 assert type(value) in [list, tuple], value
85 assert len(value) == 2, value
86 return '%s/%s' % value
87