1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 """convert to and from fractions
19 """
20
21 __version__ = "$Rev$"
22
23 import math
24
25
27 """
28 Returns the greatest common divisor of two integers.
29
30 @type a: int
31 @type b: int
32
33 @rtype : int
34 """
35 while b:
36 a, b = b, a % b
37
38 return a
39
40
42 """
43 Converts a value to a fraction
44
45 @param value: the value to convert to a tuple
46 @type value: one of
47 - string, unicode
48 - number, eg int/float/long
49 - two sized tuple
50
51 @returns: the fraction
52 @rtype: a two sized tuple with 2 integers
53 """
54
55 def _frac(num, denom=1):
56 return int(num), int(denom)
57
58 if isinstance(value, basestring):
59 noSlashes = value.count('/')
60 if noSlashes == 0:
61 parts = [value]
62 elif noSlashes == 1:
63 parts = value.split('/')
64 else:
65 raise ValueError('Expected at most one /, not %r' % (value, ))
66 return _frac(*parts)
67 elif isinstance(value, tuple):
68 if len(value) != 2:
69 raise ValueError(
70 "Can only convert two sized tuple to fraction")
71 return value
72 elif isinstance(value, (int, long)):
73 return _frac(value)
74 elif isinstance(value, float):
75 ipart = int(value)
76 fpart = value - ipart
77
78 if not fpart:
79 return _frac(value)
80 else:
81 den = math.pow(10, len(str(fpart))-2)
82 num = value*den
83 div = gcd(num, den)
84 return _frac(num/div, den/div)
85 else:
86 raise ValueError(
87 "Cannot convert %r of type %s to a fraction" % (
88 value, type(value).__name__))
89
90
92 """
93 Converts a fraction to a float
94 @param value: the value to convert to a tuple, can be one of:
95 @type value: a two sized tuple with 2 integers
96 @returns: fraction representation in float
97 @rtype: float
98 """
99 assert type(value) in [list, tuple], value
100 assert len(value) == 2, value
101 return float(value[0]) / float(value[1])
102
103
105 """
106 Converts a fraction to a string
107 @param value: the value to convert to a tuple, can be one of:
108 @type value: a two sized tuple with 2 integers
109 @returns: fraction representation as a string
110 @rtype: string
111 """
112 assert type(value) in [list, tuple], value
113 assert len(value) == 2, value
114 return '%s/%s' % value
115