[Tutor] rational number representation in Python

Gregor Lingl glingl@mail.rg16.asn-wien.ac.at
Thu, 03 May 2001 10:26:35 +0200


<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
As code for Euclid's algorithm mentioned below you could use:
<p><tt>def gcd(a,b):</tt>
<br><tt>&nbsp;&nbsp;&nbsp; "returns greates common divisor of positive
integers a and b"</tt>
<br><tt>&nbsp;&nbsp;&nbsp; while b:</tt>
<br><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; a, b = b, a%b</tt>
<br><tt>&nbsp;&nbsp;&nbsp; return a</tt><tt></tt>
<p><tt>G.L.</tt>
<br><tt></tt>&nbsp;
<br>&nbsp;
<p>Sheila King schrieb:
<blockquote TYPE=CITE>On Wed, 02 May 2001 11:58:22 -0500, "Julieta Rangel"
<br>&lt;julieta_rangel@hotmail.com>&nbsp; wrote about [Tutor] rational
number
<br>representation in Python:
<p>:Because my result of
<br>:this division is not an integer, I don't want Python to divide.&nbsp;
I want
<br>:(3/3) to be divided, (4/1) to be divided, but I want (7/2) to be left
alone.
<br>:&nbsp; How can I do this?&nbsp; Can anyone help?
<p>In comp.lang.python, there has been talk about an experimental number
class
<br>that includes rational numbers. (I don't remember the details right
now.) You
<br>could possibly use something like that.
<p>Or, it might be instructive to write your own rational number class.
For
<br>reducing fractions, like 3/3 or even 9/3, etc... a useful algorithm
is called
<br>Euclid's Algorithm. You should be able to find the algorithm in a book
on
<br>algorithms fairly easily. It will find the GCF for you, then you can
divide it
<br>out of the numerator and denominator.
<p>I would make a test, that whenever the denominator is 1, to just stop
printing
<br>it, and let the number be output as 4 instead of 4/1.
<p>--
<br>Sheila King
<br><a href="http://www.thinkspot.net/sheila/">http://www.thinkspot.net/sheila/</a>
<br><a href="http://www.k12groups.org/">http://www.k12groups.org/</a>
<p>_______________________________________________
<br>Tutor maillist&nbsp; -&nbsp; Tutor@python.org
<br><a href="http://mail.python.org/mailman/listinfo/tutor">http://mail.python.org/mailman/listinfo/tutor</a></blockquote>
</html>