Re: A Revised Rational Proposal
John Roth [EMAIL PROTECTED] writes: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. I don't think so, as I don't see it coming up often enough to warrant implementing. However, Rational(x / y) will be an acceptable string format as fallout from accepting floating point string representations. How would that work? I though the divide would be evaluated before the function call, resulting in an exception (strings don't implement the / operator). That was a mistake on my part. It would be Rational(x, y). mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Mike Meyer] #- When combined with a floating type - either complex or float - or a #- decimal type, the result will be a TypeError. The reason for this is #- that floating point numbers - including complex - and decimals are #- already imprecise. To convert them to rational would give an I'm ok with raising TypeError when mixing with float. Bu tI think that it should interact with decimal, as decimal is not imprecise: you can go Decimal-Rational and viceversa without losing information. As I posted in a previous message: To convert a Decimal to Rational, just take the number and divide it by 1E+n: Decimal(5) - Rational(5) Decimal(5.35) - Rational(535, 100) To convert a Rational to a Decimal, it would be a good idea to have a method that converts the Rational to a Decimal string... Rational(5).tostring(6) - 5.0 Rational(4, 5).tostring(3) - 0.80 Rational(5321351343, 2247313131).tostring(5000) - whatever ... and then take that string as input to Decimal and it will work. #- - Should raising a rational to a non-integer rational #- silently produce #- a float, or raise an InvalidOperation exception? I think that it never should decay into float silently. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Dan Bishop] #- I disagree with raising a TypeError here. If, in mixed-type #- expressions, we treat ints as a special case of rationals, it's #- inconsistent for rationals to raise TypeErrors in situations #- where int #- doesn't. I think it never should interact with float. Rational is being precise by nature, and it should be made explicit when losing information (by the user, using float() to the Rational or str() or repr() to the float). . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Dan Bishop] #- * Binary operators with one Rational operand and one float or Decimal #- operand will not raise a TypeError, but return a float or Decimal. I think this is a mistake. Rational should never interact with float. #- * Expressions of the form Decimal op Rational do not work. This is a #- bug in the decimal module. Can you tell me where? (or submit a bug in SF). Thanks. #- * The constructor only accepts ints and longs. Conversions #- from float #- or Decimal to Rational can be made with the static methods: #- - fromExactFloat: exact conversion from float to Rational What ExactFloat means to you? For example, what should Rational.fromExactFloat(1.1) should return? And we starting here the same long discussion that lead decimal to not be created from float because it never would be clear what it will do. #- - fromExactDecimal: exact conversion from Decimal to Rational Rational already is created from strings like 2.33, so use str() over the Decimal, not a special method: import decimal decimal.Decimal(3.44) Decimal(3.44) str(decimal.Decimal(3.44)) '3.44' import rational rational.Rational(str(decimal.Decimal(3.44))) Rational(344 / 100) . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Dan Bishop wrote: Steven Bethard wrote: Dan Bishop wrote: Mike Meyer wrote: PEP: XXX I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: No problem. Implementation of rational arithmetic. [Yards of unusable code] I'd also request that you change all leading tabs to four spaces! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike ... or making them old-style classes, which is discouraged. Since when is use of old-style classes discouraged? Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Skip Montanaro wrote: Mike ... or making them old-style classes, which is discouraged. Since when is use of old-style classes discouraged? Well, since new-style classes came along, surely? I should have thought the obvious way to move forward was to only use old-style classes when their incompatible-with-type-based-classes behavior is absolutely required. Though personally I should have said use of new-style classes is encouraged. I agree that there's no real need to change existing code just for the sake of it, but it would be interesting to see just how much existing code fails when preceded by the 1.5.2--to-2.4-compatible (?) __metaclass__ = type guessing-not-that-much-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. I don't think so, as I don't see it coming up often enough to warrant implementing. However, Rational(x / y) will be an acceptable string format as fallout from accepting floating point string representations. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Skip Montanaro [EMAIL PROTECTED] writes: Mike ... or making them old-style classes, which is discouraged. Since when is use of old-style classes discouraged? I was under the imperssion that old-style classes were going away, and hence discouraged for new library modules. However, a way to deal with this cleanly has been suggested by Steven Bethard, so the point is moot for this discussion. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
RE: A Revised Rational Proposal
Title: RE: A Revised Rational Proposal [Mike Meyer] #- I don't think so, as I don't see it coming up often enough to warrant #- implementing. However, Rational(x / y) will be an acceptable #- string format as fallout from accepting floating point string #- representations. Remember that repr() should comply with eval() to assure that x == eval(repr(x)). 'Rational(x / y)' won't comply it, as eval will raise TypeError: unsupported operand type(s) for /: 'str' and 'str'. . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? Sounds fine to me. On the str() front, I was wondering if Rational(x / y) should be an acceptable string input format. I don't think so, as I don't see it coming up often enough to warrant implementing. However, Rational(x / y) will be an acceptable string format as fallout from accepting floating point string representations. How would that work? I though the divide would be evaluated before the function call, resulting in an exception (strings don't implement the / operator). John Roth mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer wrote: This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python ... Implicit Construction - When combined with a floating type - either complex or float - or a decimal type, the result will be a TypeError. The reason for this is that floating point numbers - including complex - and decimals are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. The proper way to add a rational to one of these types is to convert the rational to that type explicitly before doing the operation. I disagree with raising a TypeError here. If, in mixed-type expressions, we treat ints as a special case of rationals, it's inconsistent for rationals to raise TypeErrors in situations where int doesn't. 2 + 0.5 2.5 Rational(2) + 0.5 TypeError: unsupported operand types for +: 'Rational' and 'float' -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Dan Bishop [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Mike Meyer wrote: This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python ... Implicit Construction - When combined with a floating type - either complex or float - or a decimal type, the result will be a TypeError. The reason for this is that floating point numbers - including complex - and decimals are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. The proper way to add a rational to one of these types is to convert the rational to that type explicitly before doing the operation. I disagree with raising a TypeError here. If, in mixed-type expressions, we treat ints as a special case of rationals, it's inconsistent for rationals to raise TypeErrors in situations where int doesn't. 2 + 0.5 2.5 Rational(2) + 0.5 TypeError: unsupported operand types for +: 'Rational' and 'float' I agree that the direction of coercion should be toward the floating type, but Decimal doesn't combine with Float either. It should be both or neither. John Roth John Roth -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer wrote: This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python ... Implementation == There is currently a rational module distributed with Python, and a second rational module in the Python cvs source tree that is not distributed. While one of these could be chosen and made to conform to the specification, I am hoping that several people will volunteer implementatins so that a ''best of breed'' implementation may be chosen. I'll be the first to volunteer an implementation. I've made the following deviations from your PEP: * Binary operators with one Rational operand and one float or Decimal operand will not raise a TypeError, but return a float or Decimal. * Expressions of the form Decimal op Rational do not work. This is a bug in the decimal module. * The constructor only accepts ints and longs. Conversions from float or Decimal to Rational can be made with the static methods: - fromExactFloat: exact conversion from float to Rational - fromExactDecimal: exact conversion from Decimal to Rational - approxSmallestDenominator: Minimizes the result's denominator, given a maximum allowed error. - approxSmallestError: Minimizes the result's error, given a maximum allowed denominator. For example, Rational.fromExactFloat(math.pi) Rational(884279719003555, 281474976710656) decimalPi = Decimal(3.141592653589793238462643383) Rational.fromExactDecimal(decimalPi) Rational(3141592653589793238462643383, 1000) Rational.approxSmallestDenominator(math.pi, 0.01) Rational(22, 7) Rational.approxSmallestDenominator(math.pi, 0.001) Rational(201, 64) Rational.approxSmallestDenominator(math.pi, 0.0001) Rational(333, 106) Rational.approxSmallestError(math.pi, 10) Rational(22, 7) Rational.approxSmallestError(math.pi, 100) Rational(311, 99) Rational.approxSmallestError(math.pi, 1000) Rational(355, 113) Anyhow, here's my code: from __future__ import division import decimal import math def _gcf(a, b): Returns the greatest common factor of a and b. a = abs(a) b = abs(b) while b: a, b = b, a % b return a class Rational(object): Exact representation of rational numbers. def __init__(self, numerator, denominator=1): Contructs the Rational object for numerator/denominator. if not isinstance(numerator, (int, long)): raise TypeError('numerator must have integer type') if not isinstance(denominator, (int, long)): raise TypeError('denominator must have integer type') if not denominator: raise ZeroDivisionError('rational construction') factor = _gcf(numerator, denominator) self.__n = numerator // factor self.__d = denominator // factor if self.__d 0: self.__n = -self.__n self.__d = -self.__d def __repr__(self): if self.__d == 1: return Rational(%d) % self.__n else: return Rational(%d, %d) % (self.__n, self.__d) def __str__(self): if self.__d == 1: return str(self.__n) else: return %d/%d % (self.__n, self.__d) def __hash__(self): try: return hash(float(self)) except OverflowError: return hash(long(self)) def __float__(self): return self.__n / self.__d def __int__(self): if self.__n 0: return -int(-self.__n // self.__d) else: return int(self.__n // self.__d) def __long__(self): return long(int(self)) def __nonzero__(self): return bool(self.__n) def __pos__(self): return self def __neg__(self): return Rational(-self.__n, self.__d) def __abs__(self): if self.__n 0: return -self else: return self def __add__(self, other): if isinstance(other, Rational): return Rational(self.__n * other.__d + self.__d * other.__n, self.__d * other.__d) elif isinstance(other, (int, long)): return Rational(self.__n + self.__d * other, self.__d) elif isinstance(other, (float, complex)): return float(self) + other elif isinstance(other, decimal.Decimal): return self.decimal() + other else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, Rational): return Rational(self.__n * other.__d - self.__d * other.__n, self.__d * other.__d) elif isinstance(other, (int, long)): return Rational(self.__n - self.__d * other, self.__d) elif isinstance(other, (float, complex)): return float(self) - other elif isinstance(other, decimal.Decimal): return self.decimal() - other else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, long)): return Rational(other * self.__d - self.__n, self.__d) elif isinstance(other, (float, complex)): return other - float(self) elif isinstance(other, decimal.Decimal): return other - self.decimal() else: return NotImplemented def __mul__(self, other): if isinstance(other, Rational): return Rational(self.__n * other.__n, self.__d * other.__d) elif isinstance(other, (int, long)): return Rational(self.__n * other, self.__d) elif isinstance(other, (float, complex)): return float(self) * other elif isinstance(other, decimal.Decimal): return self.decimal() * other else: return NotImplemented __rmul__ = __mul__
Re: A Revised Rational Proposal
Dan Bishop wrote: Mike Meyer wrote: This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python ... Implementation == There is currently a rational module distributed with Python, and a second rational module in the Python cvs source tree that is not distributed. While one of these could be chosen and made to conform to the specification, I am hoping that several people will volunteer implementatins so that a ''best of breed'' implementation may be chosen. I'll be the first to volunteer an implementation. The new Google Groups software appears to have problems with indentation. I'm posting my code again, with indents replaced with instructions on how much to indent. from __future__ import division import decimal import math def _gcf(a, b): {indent 1}Returns the greatest common factor of a and b. {indent 1}a = abs(a) {indent 1}b = abs(b) {indent 1}while b: {indent 2}a, b = b, a % b {indent 1}return a class Rational(object): {indent 1}Exact representation of rational numbers. {indent 1}def __init__(self, numerator, denominator=1): {indent 2}Contructs the Rational object for numerator/denominator. {indent 2}if not isinstance(numerator, (int, long)): {indent 3}raise TypeError('numerator must have integer type') {indent 2}if not isinstance(denominator, (int, long)): {indent 3}raise TypeError('denominator must have integer type') {indent 2}if not denominator: {indent 3}raise ZeroDivisionError('rational construction') {indent 2}factor = _gcf(numerator, denominator) {indent 2}self.__n = numerator // factor {indent 2}self.__d = denominator // factor {indent 2}if self.__d 0: {indent 3}self.__n = -self.__n {indent 3}self.__d = -self.__d {indent 1}def __repr__(self): {indent 2}if self.__d == 1: {indent 3}return Rational(%d) % self.__n {indent 2}else: {indent 3}return Rational(%d, %d) % (self.__n, self.__d) {indent 1}def __str__(self): {indent 2}if self.__d == 1: {indent 3}return str(self.__n) {indent 2}else: {indent 3}return %d/%d % (self.__n, self.__d) {indent 1}def __hash__(self): {indent 2}try: {indent 3}return hash(float(self)) {indent 2}except OverflowError: {indent 3}return hash(long(self)) {indent 1}def __float__(self): {indent 2}return self.__n / self.__d {indent 1}def __int__(self): {indent 2}if self.__n 0: {indent 3}return -int(-self.__n // self.__d) {indent 2}else: {indent 3}return int(self.__n // self.__d) {indent 1}def __long__(self): {indent 2}return long(int(self)) {indent 1}def __nonzero__(self): {indent 2}return bool(self.__n) {indent 1}def __pos__(self): {indent 2}return self {indent 1}def __neg__(self): {indent 2}return Rational(-self.__n, self.__d) {indent 1}def __abs__(self): {indent 2}if self.__n 0: {indent 3}return -self {indent 2}else: {indent 3}return self {indent 1}def __add__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__d + self.__d * other.__n, self.__d * other.__d) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n + self.__d * other, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) + other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() + other {indent 2}else: {indent 3}return NotImplemented {indent 1}__radd__ = __add__ {indent 1}def __sub__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__d - self.__d * other.__n, self.__d * other.__d) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n - self.__d * other, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) - other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() - other {indent 2}else: {indent 3}return NotImplemented {indent 1}def __rsub__(self, other): {indent 2}if isinstance(other, (int, long)): {indent 3}return Rational(other * self.__d - self.__n, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return other - float(self) {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return other - self.decimal() {indent 2}else: {indent 3}return NotImplemented {indent 1}def __mul__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__n, self.__d * other.__d) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n * other, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) * other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() * other {indent 2}else: {indent 3}return NotImplemented {indent 1}__rmul__ = __mul__ {indent 1}def __truediv__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__d, self.__d * other.__n) {indent 2}elif isinstance(other,
Re: A Revised Rational Proposal
Dan Bishop wrote: Mike Meyer wrote: PEP: XXX I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: Use PEP 257[1] docstring conventions, e.g. triple-quoted strings. Use PEP 8[2] naming conventions, e.g. name functions from_exact_float, approx_smallest_denominator, etc. The decimal and math modules should probably be imported as _decimal and _math. This will keep them from showing up in the module namespace in editors like PythonWin. I would be inclined to name the instance variables _n and _d instead of the double-underscore versions. There was a thread a few months back about avoiding overuse of __x name-mangling, but I can't find it. It also might be nice for subclasses of Rational to be able to easily access _n and _d. Thanks again for your work! Steve [1] http://www.python.org/peps/pep-0257.html [2] http://www.python.org/peps/pep-0008.html -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Steven Bethard [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Dan Bishop wrote: Mike Meyer wrote: PEP: XXX I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: Use PEP 257[1] docstring conventions, e.g. triple-quoted strings. Use PEP 8[2] naming conventions, e.g. name functions from_exact_float, approx_smallest_denominator, etc. The decimal and math modules should probably be imported as _decimal and _math. This will keep them from showing up in the module namespace in editors like PythonWin. I would be inclined to name the instance variables _n and _d instead of the double-underscore versions. There was a thread a few months back about avoiding overuse of __x name-mangling, but I can't find it. It also might be nice for subclasses of Rational to be able to easily access _n and _d. I'd suggest making them public rather than either protected or private. There's a precident with the complex module, where the real and imaginary parts are exposed as .real and .imag. John Roth Thanks again for your work! Steve [1] http://www.python.org/peps/pep-0257.html [2] http://www.python.org/peps/pep-0008.html -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Steven Bethard wrote: Dan Bishop wrote: Mike Meyer wrote: PEP: XXX I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: No problem. Implementation of rational arithmetic. from __future__ import division import decimal as decimal import math as _math def _gcf(a, b): Returns the greatest common factor of a and b. a = abs(a) b = abs(b) while b: a, b = b, a % b return a class Rational(object): This class provides an exact representation of rational numbers. All of the standard arithmetic operators are provided. In mixed-type expressions, an int or a long can be converted to a Rational without loss of precision, and will be done as such. Rationals can be implicity (using binary operators) or explicity (using float(x) or x.decimal()) converted to floats or Decimals; this may cause a loss of precision. The reverse conversions can be done without loss of precision, and are performed with the from_exact_float and from_exact decimal static methods. However, because of rounding error in the original values, this tends to produce ugly fractions. Nicer conversions to Rational can be made with approx_smallest_denominator or approx_smallest_error. def __init__(self, numerator, denominator=1): Contructs the Rational object for numerator/denominator. if not isinstance(numerator, (int, long)): raise TypeError('numerator must have integer type') if not isinstance(denominator, (int, long)): raise TypeError('denominator must have integer type') if not denominator: raise ZeroDivisionError('rational construction') factor = _gcf(numerator, denominator) self._n = numerator // factor self._d = denominator // factor if self._d 0: self._n = -self._n self._d = -self._d def __repr__(self): if self._d == 1: return Rational(%d) % self._n else: return Rational(%d, %d) % (self._n, self._d) def __str__(self): if self._d == 1: return str(self._n) else: return %d/%d % (self._n, self._d) def __hash__(self): try: return hash(float(self)) except OverflowError: return hash(long(self)) def __float__(self): return self._n / self._d def __int__(self): if self._n 0: return -int(-self._n // self._d) else: return int(self._n // self._d) def __long__(self): return long(int(self)) def __nonzero__(self): return bool(self._n) def __pos__(self): return self def __neg__(self): return Rational(-self._n, self._d) def __abs__(self): if self._n 0: return -self else: return self def __add__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d + self._d * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n + self._d * other, self._d) elif isinstance(other, (float, complex)): return float(self) + other elif isinstance(other, _decimal.Decimal): return self.decimal() + other else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d - self._d * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n - self._d * other, self._d) elif isinstance(other, (float, complex)): return float(self) - other elif isinstance(other, _decimal.Decimal): return self.decimal() - other else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, long)): return Rational(other * self._d - self._n, self._d) elif isinstance(other, (float, complex)): return other - float(self) elif isinstance(other, _decimal.Decimal): return other - self.decimal() else: return NotImplemented def __mul__(self, other): if isinstance(other, Rational): return Rational(self._n * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n * other, self._d) elif isinstance(other, (float, complex)): return float(self) * other elif isinstance(other, _decimal.Decimal): return self.decimal() * other else: return NotImplemented __rmul__ = __mul__ def __truediv__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d, self._d * other._n) elif isinstance(other, (int, long)): return Rational(self._n, self._d * other) elif isinstance(other, (float, complex)): return float(self) / other elif isinstance(other, _decimal.Decimal): return self.decimal() / other else: return NotImplemented __div__ = __truediv__ def __rtruediv__(self, other): if isinstance(other, (int, long)): return Rational(other * self._d, self._n) elif isinstance(other, (float, complex)): return other / float(self) elif isinstance(other, _decimal.Decimal): return other / self.decimal() else: return NotImplemented __rdiv__ = __rtruediv__ def __floordiv__(self, other): truediv = self / other if isinstance(truediv, Rational): return truediv._n // truediv._d else: return truediv // 1 def __rfloordiv__(self, other): return (other / self) // 1 def __mod__(self, other): return self - self // other * other def __rmod__(self, other): return other - other // self * self def _divmod__(self,
Re: A Revised Rational Proposal
Mike Meyer wrote: Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have the same behaviour as str() and Tim Peters proposes that str() behave like the to-scientific-string operation from the Spec. This looks like a C P leftover from the Decimal PEP :) Otherwise, looks good. Regards, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Dan Bishop wrote: Mike Meyer wrote: This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python ... Implicit Construction - When combined with a floating type - either complex or float - or a decimal type, the result will be a TypeError. The reason for this is that floating point numbers - including complex - and decimals are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. The proper way to add a rational to one of these types is to convert the rational to that type explicitly before doing the operation. I disagree with raising a TypeError here. If, in mixed-type expressions, we treat ints as a special case of rationals, it's inconsistent for rationals to raise TypeErrors in situations where int doesn't. 2 + 0.5 2.5 Rational(2) + 0.5 TypeError: unsupported operand types for +: 'Rational' and 'float' Mike's use of this approach was based on the discussion around PEP 327 (Decimal). The thing with Decimal and Rational is that they're both about known precision. For Decimal, the decision was made that any operation that might lose that precision should never be implicit. Getting a type error gives the programmer a choice: 1. Take the precision loss in the result, by explicitly converting the Rational to the imprecise type 2. Explicitly convert the non-Rational input to a Rational before the operation. Permitting implicit conversion in either direction opens the door to precision bugs - silent errors that even rigorous unit testing may not detect. The seemingly benign ability to convert longs to floats implicitly is already a potential source of precision bugs: Py bignum = 2 ** 62 Py bignum 4611686018427387904L Py bignum + 1.0 4.6116860184273879e+018 Py float(bignum) != bignum + 1.0 False Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Dan Bishop [EMAIL PROTECTED] writes: Mike Meyer wrote: This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python ... Implementation == There is currently a rational module distributed with Python, and a second rational module in the Python cvs source tree that is not distributed. While one of these could be chosen and made to conform to the specification, I am hoping that several people will volunteer implementatins so that a ''best of breed'' implementation may be chosen. I'll be the first to volunteer an implementation. I've already got two implementations. Both vary from the PEP. I've made the following deviations from your PEP: * Binary operators with one Rational operand and one float or Decimal operand will not raise a TypeError, but return a float or Decimal. * Expressions of the form Decimal op Rational do not work. This is a bug in the decimal module. * The constructor only accepts ints and longs. Conversions from float or Decimal to Rational can be made with the static methods: - fromExactFloat: exact conversion from float to Rational - fromExactDecimal: exact conversion from Decimal to Rational - approxSmallestDenominator: Minimizes the result's denominator, given a maximum allowed error. - approxSmallestError: Minimizes the result's error, given a maximum allowed denominator. For example, Part of finishing the PEP will be modifying the chosen contribution so that it matches the PEP. As the PEP champion, I'll take that one (and also write a test module) before submitting the PEP to the pep list for inclusion and possible finalization. If you still wish to contribute your code, please mail it to me as an attachment. Thanks, mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
John Roth [EMAIL PROTECTED] writes: I'd suggest making them public rather than either protected or private. There's a precident with the complex module, where the real and imaginary parts are exposed as .real and .imag. This isn't addressed in the PEP, and is an oversight on my part. I'm against making them public, as Rational's should be immutable. Making the two features public invites people to change them, meaning that machinery has to be put in place to prevent that. That means either making all attribute access go through __getattribute__ for new-style classes, or making them old-style classes, which is discouraged. If the class is reimplented in C, making them read-only attributes as they are in complex makes sense, and should be considered at that time. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have the same behaviour as str() and Tim Peters proposes that str() behave like the to-scientific-string operation from the Spec. This looks like a C P leftover from the Decimal PEP :) Yup. Thank you. This now reads: Regarding str() and repr() behaviour, repr() will be either ''rational(num)'' if the denominator is one, or ''rational(num, denom)'' if the denominator is not one. str() will be either ''num'' if the denominator is one, or ''(num / denom)'' if the denominator is not one. Is that acceptable? mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A Revised Rational Proposal
Mike Meyer wrote: John Roth [EMAIL PROTECTED] writes: I'd suggest making them public rather than either protected or private. There's a precident with the complex module, where the real and imaginary parts are exposed as .real and .imag. This isn't addressed in the PEP, and is an oversight on my part. I'm against making them public, as Rational's should be immutable. Making the two features public invites people to change them, meaning that machinery has to be put in place to prevent that. That means either making all attribute access go through __getattribute__ for new-style classes, or making them old-style classes, which is discouraged. Can't you just use properties? class Rational(object): ... def num(): ... def get(self): ... return self._num ... return dict(fget=get) ... num = property(**num()) ... def denom(): ... def get(self): ... return self._denom ... return dict(fget=get) ... denom = property(**denom()) ... def __init__(self, num, denom): ... self._num = num ... self._denom = denom ... r = Rational(1, 2) r.denom 2 r.num 1 r.denom = 2 Traceback (most recent call last): File interactive input, line 1, in ? AttributeError: can't set attribute Steve -- http://mail.python.org/mailman/listinfo/python-list
A Revised Rational Proposal
This version includes the input from various and sundry people. Thanks to everyone who contributed. mike PEP: XXX Title: A rational number module for Python Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Mike Meyer [EMAIL PROTECTED] Status: Draft Type: Staqndards Content-Type: text/x-rst Created: 16-Dec-2004 Python-Version: 2.5 Post-History: 15-Dec-2004, 25-Dec-2004 Contents * Abstract * Motivation * Rationale + Conversions + Python usability * Specification + Explicit Construction + Implicit Construction + Operations + Exceptions * Open Issues * Implementation * References Abstract This PEP proposes a rational number module to add to the Python standard library. Motivation = Rationals are a standard mathematical concept, included in a variety of programming languages already. Python, which comes with 'batteries included' should not be deficient in this area. When the subject was brought up on comp.lang.python several people mentioned having implemented a rational number module, one person more than once. In fact, there is a rational number module distributed with Python as an example module. Such repetition shows the need for such a class in the standard library. n There are currently two PEPs dealing with rational numbers - 'Adding a Rational Type to Python' [#PEP-239] and 'Adding a Rational Literal to Python' [#PEP-240], both by Craig and Zadka. This PEP competes with those PEPs, but does not change the Python language as those two PEPs do [#PEP-239-implicit]. As such, it should be easier for it to gain acceptance. At some future time, PEP's 239 and 240 may replace the ``rational`` module. Rationale = Conversions --- The purpose of a rational type is to provide an exact representation of rational numbers, without the imprecistion of floating point numbers or the limited precision of decimal numbers. Converting an int or a long to a rational can be done without loss of precision, and will be done as such. Converting a decimal to a rational can also be done without loss of precision, and will be done as such. A floating point number generally represents a number that is an approximation to the value as a literal string. For example, the literal 1.1 actually represents the value 1.1001 on an x86 one platform. To avoid this imprecision, floating point numbers cannot be translated to rationals directly. Instead, a string representation of the float must be used: ''Rational(%.2f % flt)'' so that the user can specify the precision they want for the floating point number. This lack of precision is also why floating point numbers will not combine with rationals using numeric operations. Decimal numbers do not have the representation problems that floating point numbers have. However, they are rounded to the current context when used in operations, and thus represent an approximation. Therefore, a decimal can be used to explicitly construct a rational, but will not be allowed to implicitly construct a rational by use in a mixed arithmetic expression. Python Usability - * Rational should support the basic arithmetic (+, -, *, /, //, **, %, divmod) and comparison (==, !=, , , =, =, cmp) operators in the following cases (check Implicit Construction to see what types could OtherType be, and what happens in each case): + Rational op Rational + Rational op otherType + otherType op Rational + Rational op= Rational + Rational op= otherType * Rational should support unary operators (-, +, abs). * repr() should round trip, meaning that: m = Rational(...) m == eval(repr(m)) * Rational should be immutable. * Rational should support the built-in methods: + min, max + float, int, long + str, repr + hash + bool (0 is false, otherwise true) When it comes to hashes, it is true that Rational(25) == 25 is True, so hash(Rational (25)) should be equal to hash(25). The detail is that you can NOT compare Rational to floats, strings or decimals, so we do not worry about them giving the same hashes. In short: hash(n) == hash(Rational(n)) # Only if n is int, long or Rational Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have the same behaviour as str() and Tim Peters proposes that str() behave like the to-scientific-string operation from the Spec. Specification = Explicit Construction - The module shall be ``rational``, and the class ``Rational``, to follow the example of the decimal [#PEP-327] module. The class creation method shall accept as arguments a numerator, and an optional denominator, which defaults to one. Both the numerator and denominator - if present - must be of integer or decimal type, or a string representation of a floating point number. The string representation of a floating point number will be converted to rational without being converted to float to preserve the accuracy of the number.
Re: A rational proposal
Mike Meyer wrote: Well, you want to be able to add floats to rationals. The results shouldn't be rational, for much the same reason as you don't want to convert floats to rationals directly. I figure the only choice that leaves is that the result be a float. That and float(rational) should be the only times that a rational gets turned into a float. Are you suggestiong that float(rational) should be a string, with the number of degrees of precesion set by something like the Context type in Decimal? Actually, I was misremembering how Decimal worked - it follows the rule you suggest: float() + Decimal() fails with a TypeError float() + float(Decimal()) works fine And I believe Decimal's __float__ operation is a 'best effort' kind of thing, so I have no problem with Rationals working the same way. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Nick Coghlan [EMAIL PROTECTED] writes: Actually, I was misremembering how Decimal worked - it follows the rule you suggest: float() + Decimal() fails with a TypeError float() + float(Decimal()) works fine And I believe Decimal's __float__ operation is a 'best effort' kind of thing, so I have no problem with Rationals working the same way. Actually, I suggested that: float() + Rational() returns float You're suggesting that the implicit conversion to float not happen here, and the user be forced to cast it to float? And you're saying Decimal does it that way.[ That's good enough for me. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Mike Meyer wrote: Actually, I suggested that: float() + Rational() returns float You're suggesting that the implicit conversion to float not happen here, and the user be forced to cast it to float? And you're saying Decimal does it that way.[ Yup. I had another look at PEP 327 (the section on implicit construction) and the reasoning that got us to that behaviour wasn't quite what I thought. However, I think the point still holds for Rational - the conversion often won't be exact in either direction, so it's OK for Python to ask the programmer to confirm that they really want to make the conversion. I think adding subsections modelled on PEP 327's Explicit construction, Implicit construction and Python usability would be a big plus for the new Rational PEP. The layout Facundo used makes it obvious that issues of playing well with other types have been considered properly. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Mike Meyer wrote: I'm willing to do the work to get decimals working properly with it. Facundo's post reminded me of some of the discussion about the interaction between floats and Decimal that went on when he was developing the module that eventually made it into the standard library. Perhaps Rational should have the same arm's length interaction with floats that Decimal does - require the user to set the precision they want by turning the float into a string that is then fed to the Rational constructor. My argument is that the following behaviour might be a little disconcerting: Py x = 1.1 Py Rational(x) Rational(11001 / 1) as opposed to: Py x = 1.1 Py Rational(%.2f % x) Rational(11 / 10) (A direct Decimal-Rational conversion should be OK, however, since it should match standard expections regarding the behaviour of the fractional portion) The other point is that, since converting a Rational to float() or Decimal() may lose information, this is something that Python shouldn't really do automatically. As Facundo suggested, a string representation is a suitable intermediate format that makes explicit the degree of precision used in the conversion. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Nick Coghlan [EMAIL PROTECTED] writes: Mike Meyer wrote: I'm willing to do the work to get decimals working properly with it. Facundo's post reminded me of some of the discussion about the interaction between floats and Decimal that went on when he was developing the module that eventually made it into the standard library. Perhaps Rational should have the same arm's length interaction with floats that Decimal does - require the user to set the precision they want by turning the float into a string that is then fed to the Rational constructor. My argument is that the following behaviour might be a little disconcerting: Py x = 1.1 Py Rational(x) Rational(11001 / 1) Yeah. That's why the spec specified integers for the argumetns. as opposed to: Py x = 1.1 Py Rational(%.2f % x) Rational(11 / 10) (A direct Decimal-Rational conversion should be OK, however, since it should match standard expections regarding the behaviour of the fractional portion) Yeah. I've already added that to my copy of the PEP. That makes rationals like (1/1E1000) much easier to represent properly. The other point is that, since converting a Rational to float() or Decimal() may lose information, this is something that Python shouldn't really do automatically. As Facundo suggested, a string representation is a suitable intermediate format that makes explicit the degree of precision used in the conversion. Well, you want to be able to add floats to rationals. The results shouldn't be rational, for much the same reason as you don't want to convert floats to rationals directly. I figure the only choice that leaves is that the result be a float. That and float(rational) should be the only times that a rational gets turned into a float. Are you suggestiong that float(rational) should be a string, with the number of degrees of precesion set by something like the Context type in Decimal? mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
I've been thinking about doing this for a while. cRat (http://sf.net/projects/pythonic) already meets these qualifications except that I need to add decimal support to it now that decimals are in the language. I could rewrite the existing code in Python (it's currently in C), but there are some very real performance reasons to do it in C rather than Python (i.e. I'm manipulating the internals of the numerator and denominator by hand for performance in the GCD function) -- Christopher A. Craig [EMAIL PROTECTED] I affirm brethren by the boasting in you which I have in Christ Jesus our Lord, I die daily I Cor 15:31 (NASB) -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
On Fri, 17 Dec 2004 21:29:52 -0600, Mike Meyer [EMAIL PROTECTED] wrote: PEP: XXX Title: A rational number module for Python Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Mike Meyer [EMAIL PROTECTED] Status: Draft Type: Staqndards Content-Type: text/x-rst Created: 16-Dec-2004 Python-Version: 2.5 Post-History: 30-Aug-2002 Abstract This PEP proposes a rational number module to add to the Python standard library. Rationale = Rationals are a standard mathematical concept, included in a variety of programming languages already. Python, which comes with 'batteries included' should not be deficient in this area. When the subject was brought up on comp.lang.python several people mentioned having implemented a rational number module, one person more than once. In fact, there is a rational number module distributed with Python as an example module. Such repetition shows the need for such a class in the standard library. There are currently two PEPs dealing with rational numbers - 'Adding a Rational Type to Python' [#PEP-239] and 'Adding a Rational Literal to Python' [#PEP-240], both by Craig and Zadka. This PEP competes with those PEPs, but does not change the Python language as those two PEPs do [#PEP-239-implicit]. As such, it should be easier for it to gain acceptance. At some future time, PEP's 239 and 240 may replace the ``rational`` module. Specification = The module shall be ``rational``, and the class ``Rational``, to follow the example of the decimal [#PEP-327] module. The class creation method shall accept as arguments a numerator, and an optional denominator, which defaults to one. Both the numerator and denominator - if present - must be of integer type. Since all other numeric types in Python are immutable, Rational objects will be immutable. Internally, the representation will insure that the numerator and denominator have a greatest common divisor of 1, and that the sign of the denominator is positive. IMO a string should also be a legitimate constructor argument, as e.g. it is for int. This also provides the opportunity to accept strings ordinarily representing floating point values and convert them to exact rationals. E.g., '1.23' is exactly 123/100 so IWT it convenient if rational.rat('1.23') == rational.rat(123, 100). This principle is easily extended to '1.23e-45' etc., since any similar otherwise-floating-point literal string can be represented exactly as a rational if integer values of numerator and denominator are not limited -- which they aren't in Python. Decimal floating point literal notation is quite handy, and it is easy and exact to convert to rational, though the reverse in not possible in general. A small further extension to literal representation is to allow two of the aforementioned style of literals to be joined with a '/' so that rat('x/y') == rat('x')/rat('y') -- i.e., you could implement this extension of literal format by just trying a literal_string.split('/') and doing the obvious. This also creates a possible general repr format that can represent any rational accurately, and the possibility if desired of a friendly __str__ format where a denominator can be made a power of 10, e.g. '0.6' where __repr__ would be '3/5'. The ``Rational`` class shall define all the standard mathematical operations: addition, subtraction, multiplication, division, modulo and power. It will also provide the methods: - max(*args): return the largest of a list of numbers and self. - min(*args): return the smallest of a list of numbers and self. - decimal(): return the decimal approximation to the rational in the current context. - inv(): Return the inverse of self. Rationals will mix with all other numeric types. When combined with an integer type, that integer will be converted to a rational before the operation. When combined with a floating type - either complex or float - the rational will be converted to a floating approximation before the operation, and a float or complex will be returned. The reason for this is that floating point numbers - including complex - are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. Decimals will be converted to rationals before the operation. [Open question: is this the right thing to do?] Sounds right, iff the decimal really does represent an exact value. But after a division or multiplication of decimals, I'm not sure I'm comfortable with calling those results exact in the same sense as if the operations had been with rationals. IMO the issue of exactness deserves particular emphasis. Otherwise why even bother with a rational type? If a decimal represents an exact value, then it should become an exact rational in operations with rationals. If you define the result of some rounding operations as exact, then you could make exact rationals from the results. E.g., the string
Re: A rational proposal
Mike Meyer wrote: John Roth [EMAIL PROTECTED] writes: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] PEP: XXX Title: A rational number module for Python ... Rationals will mix with all other numeric types. When combined with an integer type, that integer will be converted to a rational before the operation. When combined with a floating type - either complex or float - the rational will be converted to a floating approximation before the operation, and a float or complex will be returned. The reason for this is that floating point numbers - including complex - are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. Decimals will be converted to rationals before the operation. [Open question: is this the right thing to do?] I'd prefer to have rationals converted to decimals before the operation, for the same reason that they're converted to floats. Decimals also have limited precision. I'm of two minds about this one. One is that decimals have limited precision. But they represent their values exactly, You just contradicted yourself. The decimal class exactly represents numbers that have exact, concise representations in decimal, such as monetary amounts. It doesn't represent arbitary numbers exactly. Otherwise, why bother implememting a rational class? ... On the other hand, every decimal has a rational equivalent, but not vice versa. The same statement is true for floats. -- http://mail.python.org/mailman/listinfo/python-list
RE: A rational proposal
Title: RE: A rational proposal [Mike Meyer] #- Good point. Currently, objects now how to convert themselves to int, #- float and complex. Should Rational now how to convert itself to #- Decimal (and conversely, decimal now how to convert itself to #- Rational)? To convert a Decimal to Rational, just take the number and divide it by 1E+n: Decimal(5) - Rational(5) Decimal(5.35) - Rational(535, 100) To convert a Rational to a Decimal, it would be a good idea to have a method that converts the Rational to a Decimal string... Rational(5).tostring(6) - 5.0 Rational(4, 5).tostring(3) - 0.80 Rational(5321351343, 2247313131).tostring(5000) - whatever ... and then take that string as input to Decimal and it will work. . Facundo Bitácora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje. Muchas Gracias. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
[Batista, Facundo] To convert a Decimal to Rational, [...] Hi, people. I am not closely following this thread and do not know if this has been discussed before. Sorry if I'm repeating known arguments... Decimal to Rational is easy. The interesting problem is how to best convert a float to Rational. For example, do we want pi (3.1415926...) converted as 3, 22/7 or 355/113? This pretty much depends of the error we are ready to tolerate. We do not always want a hairy Rational. Given a tolerance, the question is to find the simplest Rational corresponding to a float. I once needed to solve that particular problem, and gave myself a Rational type merely (I called it Fraction). Let me append it here, in case it could be useful to your project. If you provide the constructor with a float and no tolerance, it should yield the best possible Rational for the float representation on that machine. -- François Pinard http://pinard.progiciels-bpi.ca #!/usr/bin/env python # Copyright 2000 Progiciels Bourbeau-Pinard inc. # Franois Pinard [EMAIL PROTECTED], 2000. def Fraction(num, den=1, tolerance=0): \ Return the _simplest_ fraction approximating NUM/DEN, given that the approximation error may not exceed TOLERANCE. The returned fraction has a special type which may be used in later numeric computations. if type(0.) in (type(num), type(den)): num, den = num/den, 1L while long(num) != num: num, den = 2.*num, 2L*den num = long(num) elif den 0: num = -num den = -den d = gcd(abs(num), den) value = SimplifiedFraction(num/d, den/d) if tolerance 0: value = ContinuedFraction(value, tolerance).simplify() return value class SimplifiedFraction: triples = 0 # set to 1 for a:b:c printing def __init__(self, num, den): self.num = num self.den = den def __repr__(self): num = self.num den = self.den if den == 1: return '%.f' % num if self.triples: if num 0 and num den: return '%.f:%.f:%.f' % (num / den, num % den, den) if num 0 and -num den: return '-%.f:%.f:%.f' % (-num / den, -num % den, den) return '%.f:%.f' % (num, den) def __coerce__(self, other): if isinstance(other, SimplifiedFraction): return self, other if type(other) in (type(0), type(0L)): return self, SimplifiedFraction(other, 1) if type(other) is type(0.): return float(self), other def __int__(self): if self.num 0: return -(-self.num / self.den) return self.num / self.den def __float__(self): return float(self.num) / float(self.den) def __neg__(self): return SimplifiedFraction(-self.num, self.den) def __pos__(self): return self def __abs__(self): return SimplifiedFraction(abs(self.num), self.den) def __cmp__(self, other): d = gcd(self.den, other.den) if d == 1: return cmp(self.num*other.den, other.num*self.den) return cmp(self.num*(other.den/d), other.num*(self.den/d)) def __add__(self, other): d1 = gcd(self.den, other.den) if d1 == 1: return SimplifiedFraction(self.num*other.den + other.num*self.den, self.den*other.den) t = self.num*(other.den/d1) + other.num*(self.den/d1) d2 = gcd(t, d1) return SimplifiedFraction(t/d2, (self.den/d1) * (other.den/d2)) def __sub__(self, other): d1 = gcd(self.den, other.den) if d1 == 1: return SimplifiedFraction(self.num*other.den - other.num*self.den, self.den*other.den) t = self.num*(other.den/d1) - other.num*(self.den/d1) d2 = gcd(t, d1) return SimplifiedFraction(t/d2, (self.den/d1) * (other.den/d2)) def __mul__(self, other): d1 = gcd(self.num, other.den) d2 = gcd(self.den, other.num) return SimplifiedFraction((self.num/d1) * (other.num/d2), (self.den/d2) * (other.den/d1)) def __div__(self, other): d1 = gcd(self.num, other.num) d2 = gcd(self.den, other.den) return SimplifiedFraction((self.num/d1) * (other.den/d2), (self.den/d2) * (other.num/d1)) def __radd__(self, other): return other.__add__(self) def __rsub__(self, other): return other.__sub__(self) def __rmul__(self, other): return other.__mul__(self) def __rdiv__(self, other): return other.__div__(self) def gcd(a, b): while b: a, b = b, a % b return a class ContinuedFraction: def __init__(self, value, tolerance): integer = int(value) residual = value - integer self.integers = [integer] while residual != 0 and abs(value - self.simplify()) tolerance:
Re: A rational proposal
[EMAIL PROTECTED] (Christopher A. Craig) writes: I've been thinking about doing this for a while. cRat (http://sf.net/projects/pythonic) already meets these qualifications except that I need to add decimal support to it now that decimals are in the language. I could rewrite the existing code in Python (it's currently in C), but there are some very real performance reasons to do it in C rather than Python (i.e. I'm manipulating the internals of the numerator and denominator by hand for performance in the GCD function) I hadn't considered doing a C implementation until we had experience with a Python implementation to learn from. But if you've got this and are willing to release it under a license that allows inclusion in Python, that would be great. I'm willing to do the work to get decimals working properly with it. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Raymond L. Buvel wrote: gmpy wraps GMP, which is covered by LGPL; therefore, gmpy itself is LGPL, and thus, sadly, cannot be included with python (otherwise, speaking as gmpy's author, I'd be glad to fix its design to meet your objections). Since the LGPL was designed to allow propritary software to link to a LGPL module, I don't see why any software under a free license like Python cannot link to the GMP library. The PSF may want you to release gmpy under a dual license if it is incorporated into the Python standard library but I don't see why that cannot be done. core features cannot rely on software components with restrictive licenses. nothing stops a Python distributor from shipping Python builds with LGPL'ed (or GPL'ed) components today; Alex was talking about the core distribution. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Hi Mike - Thanks for taking the time to put this together. In article [EMAIL PROTECTED], Mike Meyer wrote: - max(*args): return the largest of a list of numbers and self. - min(*args): return the smallest of a list of numbers and self. I would strongly prefer either adapting the already built-in min/max functions to support this type or creating functions in a module rather than using the method approach. My reason is the assymetry; I would much prefer: rational.max(rat1, rat2, rat3) over: rat1.max(rat2, rat3) for the simple reason that the latter looks unbalanced and empbasizes rat1 when there is really no reason to do so. Rationals will mix with all other numeric types. When combined with an integer type, that integer will be converted to a rational before the operation. When combined with a floating type - either complex or float - the rational will be converted to a floating approximation before the operation, and a float or complex will be returned. The reason for this is that floating point numbers - including complex - are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. Decimals will be converted to rationals before the operation. [Open question: is this the right thing to do?] Sounds right to me. Cheers, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. talking about music is like dancing about architecture. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Mike Meyer wrote: PEP: XXX Title: A rational number module for Python snip I think it is a good idea to have rationals as part of the standard distribution but why not base this on the gmpy module (https://sourceforge.net/projects/gmpy)? That module already provides good performance. However, it does a few things that may not be good ideas. 1. Floats are converted to rationals. I think your proposal of rational to float is better. 2. Fails with a TypeError when used with a complex. Again Your proposal provides a better solution. 3. Fractional powers fail with a ValueError if the root is not exact. You do not address this in your proposal. Could silently convert to float in this case but is it better to force the user to be explicit and use the float() operation? Ray Buvel -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Raymond L. Buvel [EMAIL PROTECTED] writes: Mike Meyer wrote: PEP: XXX Title: A rational number module for Python snip I think it is a good idea to have rationals as part of the standard distribution but why not base this on the gmpy module (https://sourceforge.net/projects/gmpy)? That module already provides good performance. However, it does a few things that may not be good ideas. It wraps a third party package, which can't really be added to the standard libraray. The documentation for a rationa number package in Python should include a pointer to gmpy with a note about performance. 3. Fractional powers fail with a ValueError if the root is not exact. You do not address this in your proposal. Could silently convert to float in this case but is it better to force the user to be explicit and use the float() operation? You're right. Raising a rational to a rational power isn't covered, and may produce an irrational answer. Raising a rational to a floating point power will cause the rational to be converted to a float, as is specified. I think forcing the use of float is wrong, as the rational may be an integer. I'm not sure what should be done, so this is being added as an open issue. Thanks, mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
John Roth [EMAIL PROTECTED] writes: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] PEP: XXX Title: A rational number module for Python The ``Rational`` class shall define all the standard mathematical operations: addition, subtraction, multiplication, division, modulo and power. It will also provide the methods: - max(*args): return the largest of a list of numbers and self. - min(*args): return the smallest of a list of numbers and self. max() and min() are already part of the standard library. Providing them as instance methods is quite irregular. They don't handle decimals or rationals. This is following the lead of the decimal package. - decimal(): return the decimal approximation to the rational in the current context. This ought to be the responsibility of the decimal() constructor. I can see including it here to avoid adding it to the decimal() constructor, but IMO it's bad design. Good point. Currently, objects now how to convert themselves to int, float and complex. Should Rational now how to convert itself to Decimal (and conversely, decimal now how to convert itself to Rational)? - inv(): Return the inverse of self. I presume this means that if the rational is x/y, then it returns y/x? Is this better wording: - inv(): Return self to the power -1. Rationals will mix with all other numeric types. When combined with an integer type, that integer will be converted to a rational before the operation. When combined with a floating type - either complex or float - the rational will be converted to a floating approximation before the operation, and a float or complex will be returned. The reason for this is that floating point numbers - including complex - are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. Decimals will be converted to rationals before the operation. [Open question: is this the right thing to do?] I'd prefer to have rationals converted to decimals before the operation, for the same reason that they're converted to floats. Decimals also have limited precision. I'm of two minds about this one. One is that decimals have limited precision. But they represent their values exactly, whereas 1E73 isn't a 1 followed by 73 zeros when converted to an int. On the other hand, every decimal has a rational equivalent, but not vice versa. Thanks, mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
On Sat, 18 Dec 2004 12:29:10 -0600, Mike Meyer [EMAIL PROTECTED] wrote: Raymond L. Buvel [EMAIL PROTECTED] writes: Mike Meyer wrote: PEP: XXX Title: A rational number module for Python snip I think it is a good idea to have rationals as part of the standard distribution but why not base this on the gmpy module (https://sourceforge.net/projects/gmpy)? That module already provides good performance. However, it does a few things that may not be good ideas. It wraps a third party package, which can't really be added to the standard libraray. The documentation for a rationa number package in Python should include a pointer to gmpy with a note about performance. This is not true. As evidence, see the following modules: readline _ssl _tkinter _curses, _curses_panel dbm, gdbm, _bsddb zlib pyexpat Not to mention the crazy, mega-platform specific modules like gl, nis, fm, sgi, and more. Nor Python's tight dependency on another third party library, libc. ;) Note I am not advocating the use of gmpy (nor the avoidance of it), simply pointing out that there is ample precedent in the standard library for dependence on third party libraries. Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
On Sat, 18 Dec 2004 12:40:04 -0600, Mike Meyer [EMAIL PROTECTED] wrote: John Roth [EMAIL PROTECTED] writes: Mike Meyer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] PEP: XXX Title: A rational number module for Python The ``Rational`` class shall define all the standard mathematical operations: addition, subtraction, multiplication, division, modulo and power. It will also provide the methods: - max(*args): return the largest of a list of numbers and self. - min(*args): return the smallest of a list of numbers and self. max() and min() are already part of the standard library. Providing them as instance methods is quite irregular. They don't handle decimals or rationals. This is following the lead of the decimal package. They do handle decimals. They handle any object which define __cmp__, or the appropriate rich comparison methods. The Decimal type seems to define min and max so that NaNs can be treated specially, but I glean this understanding from only a moment of reading decimal.py. Perhaps someone more well informed can declare definitively the purpose of these methods. Also, note that the signatures are not Decimal.max(*args) and Decimal.min(*args), but rather each takes a single decimal argument in addition to self and an optional context argument. So if the goal is symmetry with the Decimal type, then Rational.max() and Rational.min() should take only one argument. Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Raymond L. Buvel [EMAIL PROTECTED] wrote: Mike Meyer wrote: PEP: XXX Title: A rational number module for Python snip I think it is a good idea to have rationals as part of the standard distribution but why not base this on the gmpy module (https://sourceforge.net/projects/gmpy)? That module already provides gmpy wraps GMP, which is covered by LGPL; therefore, gmpy itself is LGPL, and thus, sadly, cannot be included with python (otherwise, speaking as gmpy's author, I'd be glad to fix its design to meet your objections). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
[EMAIL PROTECTED] (Alex Martelli) writes: gmpy wraps GMP, which is covered by LGPL; therefore, gmpy itself is LGPL, and thus, sadly, cannot be included with python (otherwise, speaking as gmpy's author, I'd be glad to fix its design to meet your objections). There's no obstacle to including LGPL'd modules as part of the Python distribution as long as those modules are also offered as source code. The LGPL does place some conditions on how LGPL'd modules can be further redistributed, which users would have to abide by; that might or might not be considered undesirable for Python distro purposes. There's certainly no reason the Python docs can't point to modules like gmpy. They already point to code and documentation that's flat-out proprietary. -- http://mail.python.org/mailman/listinfo/python-list
A rational proposal
PEP: XXX Title: A rational number module for Python Version: $Revision: 1.4 $ Last-Modified: $Date: 2003/09/22 04:51:50 $ Author: Mike Meyer [EMAIL PROTECTED] Status: Draft Type: Staqndards Content-Type: text/x-rst Created: 16-Dec-2004 Python-Version: 2.5 Post-History: 30-Aug-2002 Abstract This PEP proposes a rational number module to add to the Python standard library. Rationale = Rationals are a standard mathematical concept, included in a variety of programming languages already. Python, which comes with 'batteries included' should not be deficient in this area. When the subject was brought up on comp.lang.python several people mentioned having implemented a rational number module, one person more than once. In fact, there is a rational number module distributed with Python as an example module. Such repetition shows the need for such a class in the standard library. There are currently two PEPs dealing with rational numbers - 'Adding a Rational Type to Python' [#PEP-239] and 'Adding a Rational Literal to Python' [#PEP-240], both by Craig and Zadka. This PEP competes with those PEPs, but does not change the Python language as those two PEPs do [#PEP-239-implicit]. As such, it should be easier for it to gain acceptance. At some future time, PEP's 239 and 240 may replace the ``rational`` module. Specification = The module shall be ``rational``, and the class ``Rational``, to follow the example of the decimal [#PEP-327] module. The class creation method shall accept as arguments a numerator, and an optional denominator, which defaults to one. Both the numerator and denominator - if present - must be of integer type. Since all other numeric types in Python are immutable, Rational objects will be immutable. Internally, the representation will insure that the numerator and denominator have a greatest common divisor of 1, and that the sign of the denominator is positive. The ``Rational`` class shall define all the standard mathematical operations: addition, subtraction, multiplication, division, modulo and power. It will also provide the methods: - max(*args): return the largest of a list of numbers and self. - min(*args): return the smallest of a list of numbers and self. - decimal(): return the decimal approximation to the rational in the current context. - inv(): Return the inverse of self. Rationals will mix with all other numeric types. When combined with an integer type, that integer will be converted to a rational before the operation. When combined with a floating type - either complex or float - the rational will be converted to a floating approximation before the operation, and a float or complex will be returned. The reason for this is that floating point numbers - including complex - are already imprecise. To convert them to rational would give an incorrect impression that the results of the operation are precise. Decimals will be converted to rationals before the operation. [Open question: is this the right thing to do?] Rationals can be converted to floats by float(rational), and to integers by int(rational). The module will define and at times raise the following exceptions: - DivisionByZero: divide by zero - OverflowError: overflow attempting to convert to a float. Implementation == There is currently a rational module distributed with Python, and a second rational module in the Python cvs source tree that is not distributed. While one of these could be chosen and made to conform to the specification, I am hoping that several people will volunteer implementatins so that a ''best of breed'' implementation may be chosen. References == .. [#PEP-239] Adding a Rational Type to Python, Craig, Zadka (http://www.python.org/peps/pep-0239.html) .. [#PEP-240] Adding a Rational Literal to Python, Craig, Zadka (http://www.python.org/peps/pep-0240.html) .. [#PEP-327] Decimal Data Type, Batista (http://www.python.org/peps/pep-0327.html) .. [#PEP-239-implicit] PEP 240 adds a new literal type to Pytbon, PEP 239 implies that division of integers would change to return rationals. Copyright = This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: -- http://mail.python.org/mailman/listinfo/python-list
Re: A rational proposal
Mike Meyer wrote: Last-Modified: $Date: 2003/09/22 04:51:50 $ Created: 16-Dec-2004 Post-History: 30-Aug-2002 playing with the time machine? /F -- http://mail.python.org/mailman/listinfo/python-list