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: 7739 $"
26
27 import math
28
29
31 """
32 Returns the greatest common divisor of two integers.
33
34 @type a: int
35 @type b: int
36
37 @rtype : int
38 """
39 while b:
40 a, b = b, a % b
41
42 return a
43
44
46 """
47 Converts a value to a fraction
48
49 @param value: the value to convert to a tuple
50 @type value: one of
51 - string, unicode
52 - number, eg int/float/long
53 - two sized tuple
54
55 @returns: the fraction
56 @rtype: a two sized tuple with 2 integers
57 """
58
59 def _frac(num, denom=1):
60 return int(num), int(denom)
61
62 if isinstance(value, basestring):
63 noSlashes = value.count('/')
64 if noSlashes == 0:
65 parts = [value]
66 elif noSlashes == 1:
67 parts = value.split('/')
68 else:
69 raise ValueError('Expected at most one /, not %r' % (value, ))
70 return _frac(*parts)
71 elif isinstance(value, tuple):
72 if len(value) != 2:
73 raise ValueError(
74 "Can only convert two sized tuple to fraction")
75 return value
76 elif isinstance(value, (int, long)):
77 return _frac(value)
78 elif isinstance(value, float):
79 ipart = int(value)
80 fpart = value - ipart
81
82 if not fpart:
83 return _frac(value)
84 else:
85 den = math.pow(10, len(str(fpart))-2)
86 num = value*den
87 div = gcd(num, den)
88 return _frac(num/div, den/div)
89 else:
90 raise ValueError(
91 "Cannot convert %r of type %s to a fraction" % (
92 value, type(value).__name__))
93
94
96 """
97 Converts a fraction to a float
98 @param value: the value to convert to a tuple, can be one of:
99 @type value: a two sized tuple with 2 integers
100 @returns: fraction representation in float
101 @rtype: float
102 """
103 assert type(value) in [list, tuple], value
104 assert len(value) == 2, value
105 return float(value[0]) / float(value[1])
106
107
109 """
110 Converts a fraction to a string
111 @param value: the value to convert to a tuple, can be one of:
112 @type value: a two sized tuple with 2 integers
113 @returns: fraction representation as a string
114 @rtype: string
115 """
116 assert type(value) in [list, tuple], value
117 assert len(value) == 2, value
118 return '%s/%s' % value
119