Re: off topic but please forgive me me and answer



On Apr 2, 6:07 pm, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:
On Fri, 02 Apr 2010 12:35:55 -0700, Mensanator wrote:
If you want an exact result when multiplying arbitrary fractions, you
need to avoid floats and decimals and use Fractions:

Fraction(1, 2)**2

Fraction(1, 4)

Where do you get that from?

Where do I get what from? Fraction? Oops, sorry about that.

In Python2.6:

from fractions import Fraction

Ok, thanks. I've been using gmpy to do rational arithmetic:

import gmpy
gmpy.mpq(1,2)**2
mpq(1,4)

But I don't have a lot of call for it.


In older Pythons, there was a demo module Demo/classes/Rat.py but it may
not be installed on your system. Seehttp://bugs.python.org/issue1682

If you meant, where did I get the statement about exact results from,
both float and Decimal are fixed precision numbers. float precision is
fixed by the operating system and/or hardware; Decimal precision can be
arbitrarily chosen by the caller, but having made that choice,
calculations are rounded to that precision. Only Fraction gives exact
results for any arbitrary rational number.

Yes, rationals are handy sometimes.


--
Steven

.



Relevant Pages

  • Re: Precision issue
    ... Can the float handling rules of the underlying layers be ... scaling by 100 is overkill - the nearest power of two is ... should be sufficient to allow two decimal digits of precision. ... One common need for decimals is for currency values. ...
    (comp.lang.python)
  • Re: off topic but please forgive me me and answer
    ... need to avoid floats and decimals and use Fractions: ... both float and Decimal are fixed precision numbers. ... Only Fraction gives exact ...
    (comp.lang.python)
  • Re: floating-point precision
    ... The first 6 decimals are ok, ... type float just doesn't provide the precision you ...
    (comp.lang.c)
  • Re: floating-point precision
    ... The LUTs contain float numbers, and I generated the numbers very precisely, up to 10 decimals. ... I am not quite sure why that is the case, although I believe float do not have enough precision, so the compiler gives the closest approximation that can be had with float. ...
    (comp.lang.c)
  • [BUG][FIX] Float conversion #asFloat and #asTrueFraction
    ... There are several problems in Dolphin Float/Fraction conversion ... Float asTrueFraction does not handle denormalized number ... Large fractions asFloat do overflow ... Integer and Fraction #asFloat do not round to nearest Floating ...
    (comp.lang.smalltalk.dolphin)