Re: Hack request: rational numbers

2007-10-26 Thread Anton Mellit
> Hi!
>
> I am using rational numbers from the gmpy module and I find that creating
> one in Python using
>
>>>> mpq(3,4)
>
> is rather clumsy. Clearly, minimal representation of this rational number
> is
>
>3/4
>
> but in Python this expression has different meaning.

Hi,
I am writing an interface module with the PARI library and I had the
same question. So I implemented division operator for my new type
which of course did not work if both division arguments are integers.
Say 3/4 gives zero. But I discovered very simple hack. I add the
following string to my module initialization function:

PyInt_Type.tp_as_number->nb_divide = gen_div;

Here gen_div is the function I use for division of objects of my new type.

This solution is pretty nice since I do not have to make changes into
python or interactive shell. It is even better to make a function
which would 'turn on/off' my division. It is strange that it is only
possible to do such things in C code, I cannot do it from python.

Anton
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-04-27 Thread M.-A. Lemburg
On 2007-02-23 16:35, Martin Manns wrote:
> Hi,
> 
> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
> 
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):
> 
> ---
> $ python
> Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
> [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from mx.Number import *
 a=Rational(0,1)
 a
> 0/1
 str(a)
> '0.0'
 b=-50
 b
> -50L
 a==b
> __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
> False
> ---
> 
> How do I get rid of these warnings?

FYI: The next version of mxNumber will have this warning removed.

> Is there any rational number library around that
> 1) is comparably fast for large denominators
> 2) allows deriving types from Rationals without wrapping?
> 
> Regards
> 
> Martin
> 
> P.S. The respective mailing list does not like me, so that I try my
> luck here.

Why is that ? The egenix-user mailing is open for all our users.
We do require registration to stop spam from reaching the list.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Apr 27 2007)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-28 Thread Fernando Perez
[EMAIL PROTECTED] wrote:

> On Feb 25, 3:09 pm, Fernando Perez <[EMAIL PROTECTED]> wrote:

>> Alex, have you had a look at SAGE?
>>
>> http://modular.math.washington.edu/sage/
>>
>> it uses GMP extensively, so they've had to patch it to work around these
>> issues.  You can look at the SAGE release (they package everything as the
>> original tarball + patches) for the GMP-specific stuff you need, though I
>> suspect you'll still want to play with SAGE a little bit :).  It's a
>> mighty impressive system.
> 
> Thanks Fernando, I will take a look at that.

Just to save you a bit of time, if you unpack the source tarball, inside the
distro you'll find a bunch of .spkg files.  Those are really .tar.bz2 files
for each included package, containing the original plus any SAGE patches
and some install-related scripts.

The GMP .spkg has all the OSX patches, plus a few more.

Cheers,


f

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-26 Thread aleaxit
On Feb 25, 3:09 pm, Fernando Perez <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > gmpy itself is or should be pretty trivial to build on any platform
> > (and I'll always happily accept any fixes that make it better on any
> > specific platform, since it's easy to make them conditional so they'll
> > apply to that platform only), but the underlying GMP is anything but:-
> > (.
>
> Alex, have you had a look at SAGE?
>
> http://modular.math.washington.edu/sage/
>
> it uses GMP extensively, so they've had to patch it to work around these
> issues.  You can look at the SAGE release (they package everything as the
> original tarball + patches) for the GMP-specific stuff you need, though I
> suspect you'll still want to play with SAGE a little bit :).  It's a mighty
> impressive system.

Thanks Fernando, I will take a look at that.


Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-25 Thread Gabriel Genellina
En Sat, 24 Feb 2007 01:42:00 -0300, Martin Manns <[EMAIL PROTECTED]> escribió:

> On Fri, 23 Feb 2007 20:20:12 -0300
> "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>
>> mx.Number.Rational is horribly broken. They break this rule:
>> a==b => hash(a)==hash(b)
>> so they can'b be used as dictionary keys, by example.
>
> I would be interested, under which circumstances the rule is broken.
> In my (few) tests, hash(a)==hash(b) worked.

I can't reproduce this issue with the latest mx experimental package, it  
appears to be fixed now. Also, I'm currently using Python 2.5 and it was  
2.3 by that time.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-25 Thread Fernando Perez
[EMAIL PROTECTED] wrote:


> gmpy itself is or should be pretty trivial to build on any platform
> (and I'll always happily accept any fixes that make it better on any
> specific platform, since it's easy to make them conditional so they'll
> apply to that platform only), but the underlying GMP is anything but:-
> (.

Alex, have you had a look at SAGE?

http://modular.math.washington.edu/sage/

it uses GMP extensively, so they've had to patch it to work around these
issues.  You can look at the SAGE release (they package everything as the
original tarball + patches) for the GMP-specific stuff you need, though I
suspect you'll still want to play with SAGE a little bit :).  It's a mighty
impressive system.

Cheers,


f

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-25 Thread aleaxit
On Feb 24, 12:25 am, Toby A Inkster <[EMAIL PROTECTED]>
wrote:
> aleaxit wrote:
> > If anybody who has easy access to Microsoft's MSVC++.NET (and is willing
> > to try building GMP 4.2 with/for it), or a PPC Mac with XCode installed
> > (possibly with MacOSX 10.3...)
>
> I'm writing this message on a MacOS 10.3.9 box with Xcode 1.5 (gcc 3.3)
> installed. If you tell me how, I'd be happy to compile it for you.
>
> Contact me through the feedback form on the site below.

Thanks, but unfortunately getting GMP 4.2 built right on any platform
is never a trivial task -- GMP's maintainer is apparently actively
hostile to any attempts of making fixes to GMP to make it build
correctly on MAC OS X, in particular.  I have a correspondent who
thinks he's got a working patch (for PPC on MacOSX 10.4, at least);
he's very busy but I hope he'll send it to me eventually.

gmpy itself is or should be pretty trivial to build on any platform
(and I'll always happily accept any fixes that make it better on any
specific platform, since it's easy to make them conditional so they'll
apply to that platform only), but the underlying GMP is anything but:-
(.


Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-24 Thread Toby A Inkster
aleaxit wrote:

> If anybody who has easy access to Microsoft's MSVC++.NET (and is willing
> to try building GMP 4.2 with/for it), or a PPC Mac with XCode installed
> (possibly with MacOSX 10.3...)

I'm writing this message on a MacOS 10.3.9 box with Xcode 1.5 (gcc 3.3)
installed. If you tell me how, I'd be happy to compile it for you.

Contact me through the feedback form on the site below.

-- 
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Martin Manns
On 23 Feb 2007 22:19:30 -0800
[EMAIL PROTECTED] wrote:

> > Looks pretty much the same as mx.Number
> >
> > Does this warning come up from gmp? Do I have to compile it with
> > different flags?
> > Or do both wrappers use the same code?
> >
> > I would like to encourage the python community (i.e. the guys
> > maintaining the python docs) to point out a recommended rational
> > library. In one of the rational PEPs, it is stated that there are
> > multiple robust rational wrappers for python. But it is not stated,
> > which ones were thoroughly reviewed.
> >
> That specific error message is only a warning that occurs the first
> time a comparison operation is performed. I've successfully used gmpy
> and just ignored the one-time only error. You can use the "warnings"
> module to filter out that error. If I remember correctly, it was fixed
> in version 1.01. I know it is fixed in the SVN version.
> 
> Which specific version of gmpy are you using? (What is
> gmpy.version()?)
> 
$ python
Python 2.4.3 (#1, Jan 13 2007, 20:53:15) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gmpy
>>> gmpy.version()
'1.01'
>>> 

Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread casevh
> Looks pretty much the same as mx.Number
>
> Does this warning come up from gmp? Do I have to compile it with
> different flags?
> Or do both wrappers use the same code?
>
> I would like to encourage the python community (i.e. the guys
> maintaining the python docs) to point out a recommended rational
> library. In one of the rational PEPs, it is stated that there are
> multiple robust rational wrappers for python. But it is not stated,
> which ones were thoroughly reviewed.
>
That specific error message is only a warning that occurs the first
time a comparison operation is performed. I've successfully used gmpy
and just ignored the one-time only error. You can use the "warnings"
module to filter out that error. If I remember correctly, it was fixed
in version 1.01. I know it is fixed in the SVN version.

Which specific version of gmpy are you using? (What is
gmpy.version()?)

I just compiled Alex's most recent SVN version on Linux without any
problems. I'll make Windows binaries next.

casevh





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 20:20:12 -0300
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns <[EMAIL PROTECTED]>
> escribió:
> 
> > I am starting to use rationals and since I found no batteries
> > included, I tried out the mxNumber package.
> >
> > However, I get strange warnings on comparison operations
> > (which however seem to yield correct results):
> 
> mx.Number.Rational is horribly broken. They break this rule:
> 
> a==b => hash(a)==hash(b)
> 
> so they can'b be used as dictionary keys, by example.
> Try the other packages suggested. I've used clnum without problems.
> 

I would be interested, under which circumstances the rule is broken.
In my (few) tests, hash(a)==hash(b) worked.

But I will definitely try clnum.
However, I already started trying out gmpy (1.1):

$ python
Python 2.4.3 (#1, Jan 13 2007, 20:53:15) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from gmpy import *
>>> a=mpq(0,1)
>>> a
mpq(0)
>>> b=-500
>>> a==b
__main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
False
>>>

Looks pretty much the same as mx.Number

Does this warning come up from gmp? Do I have to compile it with
different flags?
Or do both wrappers use the same code?

I would like to encourage the python community (i.e. the guys
maintaining the python docs) to point out a recommended rational
library. In one of the rational PEPs, it is stated that there are
multiple robust rational wrappers for python. But it is not stated,
which ones were thoroughly reviewed.

Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 3:44 pm, [EMAIL PROTECTED] wrote:
   ...
> I can keep building gmpy for Windows. I actually use MINGW since
> getting GMP compiled under MSVC is "challanging". I should be able to
> build new binaries for Windows this weekend. And I would be happy to
> point everyone to a real release.

Great!  May I add you as a Member to the Google Code gmpy project?
After which, you should be able to use svn to get the latest sources,
make fixes, etc, etc -- including (if I understand the Google Code
mechanics correctly) simply uploading the Windows installer or
whatever, if it passes all tests (formal and informal) satisfactorily.

Please don't use the "1.02 prerelease" sources zip -- the SVN trunk is
more updated, I'll make a "1.02 definitive" sources zip once we have
gmpy built and working correctly on all variants of Windows and Mac
that we're going to support (I suggest that the binaries be made for
Python 2.3, 2.4 and 2.5, for Windows, Mac intel and Mac PPC -- unless
we can make Mac Universal work, but I'm finding that quite
problematic... a PPC Mac somewhere I shd be able to find:-).


Thanks,

Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread casevh
On Feb 23, 3:27 pm, [EMAIL PROTECTED] wrote:
> On Feb 23, 12:00 pm, [EMAIL PROTECTED] wrote:
>...
>
> > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > > cvs 10 months ago).
>
> > I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by
> > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> > has not updated cvs with the fix.
>
> Heh, I see why one might get that impression -- I'm in the process of
> moving gmpy from sourceforge (where I find it harder and harder, and
> ever more problematic, to work) to code.google.com 's new hosting
> facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and
> particularly including your fix, Case) is already available 
> athttp://code.google.com/p/gmpy/but I have made no official
> announcement yet (partly because what's available is yet limited:
> sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX
> 10.4 on Macs with intel processors)... building binaries for Windows
> (not having a Windows machine or development system) or Universal
> binaries for the Mac (due to problems building Universal versions of
> the underlying GMP in its latest, 4.2 incarnation... I'm running out
> of PPC-based Macs, and have none left with MaxOSX 10.3...) is much
> more problematic for me.
>
> To call this (Google Code) release 1.02, with a "1.04" (?) out from
> another source, may be confusing, but I'd rather not "force" the
> number upwards
>
> I do have one new co-owner on the Google Code "version" of gmpy (Chip
> Turner, once author of a similar GMP wrapper for perl, now a Python
> convert and a colleague of mine) but I suspect that won't make the
> building of Windows (and Universal Mac) binaries much easier.  If
> anybody who has easy access to Microsoft's MSVC++.NET (and is willing
> to try building GMP 4.2 with/for it), or a PPC Mac with XCode
> installed (possibly with MacOSX 10.3...), wants to volunteer to build
> "the missing binaries" for the platforms that the current owners of
> gmpy can't easily support, we could complete, test and release the
> definitive 1.02, and move on with the development (I could get
> enthusiastic about this again, if I could develop just the sources,
> and the binaries for the one architecture I really use -- Macs w/intel
> -- rather than strive each time with binaries for architectures that
> are quite a pain for me...!-).
>
> Anybody who's interested in helping out is welcome to mail me and/or
> use the "wiki" and "issues" entry of the Google Code gmpy site...
>
> Thanks,
>
> Alex

I can keep building gmpy for Windows. I actually use MINGW since
getting GMP compiled under MSVC is "challanging". I should be able to
build new binaries for Windows this weekend. And I would be happy to
point everyone to a real release.

casevh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 2:52 pm, [EMAIL PROTECTED] wrote:
> > Am I hallucinating? Didn't I see at least some version
> > of gmpy for Python 2.5 on SourceForge awhile back?
> > I distinctly remember thinking that I don't have to
> > direct people to your site, but SourceForge is not
> > showing anything beyond vesion 1.01 for Python 2.4.
>
> Alex released versions 1.02 and 1.03 as CVS updates only. I think he
> may have made an announcement that 1.02 included alpha support for
> Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there
> has been an official release, though.

Right: apparently sourceforce doesn't want me to do "releases" any
more (quite apart from the utter mess that doing a "release" on
sourceforce always was and still is), though I can still update the
cvs repository -- that's part of why I'm moving to Google Code
hosting.


Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 12:00 pm, [EMAIL PROTECTED] wrote:
   ...
> > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > cvs 10 months ago).
>
> I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.

Heh, I see why one might get that impression -- I'm in the process of
moving gmpy from sourceforge (where I find it harder and harder, and
ever more problematic, to work) to code.google.com 's new hosting
facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and
particularly including your fix, Case) is already available at
http://code.google.com/p/gmpy/ but I have made no official
announcement yet (partly because what's available is yet limited:
sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX
10.4 on Macs with intel processors)... building binaries for Windows
(not having a Windows machine or development system) or Universal
binaries for the Mac (due to problems building Universal versions of
the underlying GMP in its latest, 4.2 incarnation... I'm running out
of PPC-based Macs, and have none left with MaxOSX 10.3...) is much
more problematic for me.

To call this (Google Code) release 1.02, with a "1.04" (?) out from
another source, may be confusing, but I'd rather not "force" the
number upwards

I do have one new co-owner on the Google Code "version" of gmpy (Chip
Turner, once author of a similar GMP wrapper for perl, now a Python
convert and a colleague of mine) but I suspect that won't make the
building of Windows (and Universal Mac) binaries much easier.  If
anybody who has easy access to Microsoft's MSVC++.NET (and is willing
to try building GMP 4.2 with/for it), or a PPC Mac with XCode
installed (possibly with MacOSX 10.3...), wants to volunteer to build
"the missing binaries" for the platforms that the current owners of
gmpy can't easily support, we could complete, test and release the
definitive 1.02, and move on with the development (I could get
enthusiastic about this again, if I could develop just the sources,
and the binaries for the one architecture I really use -- Macs w/intel
-- rather than strive each time with binaries for architectures that
are quite a pain for me...!-).

Anybody who's interested in helping out is welcome to mail me and/or
use the "wiki" and "issues" entry of the Google Code gmpy site...


Thanks,

Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns <[EMAIL PROTECTED]> escribió:

> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
>
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):

mx.Number.Rational is horribly broken. They break this rule:

a==b => hash(a)==hash(b)

so they can'b be used as dictionary keys, by example.
Try the other packages suggested. I've used clnum without problems.

-- 
Gabriel Genellina

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread casevh

> Am I hallucinating? Didn't I see at least some version
> of gmpy for Python 2.5 on SourceForge awhile back?
> I distinctly remember thinking that I don't have to
> direct people to your site, but SourceForge is not
> showing anything beyond vesion 1.01 for Python 2.4.

Alex released versions 1.02 and 1.03 as CVS updates only. I think he
may have made an announcement that 1.02 included alpha support for
Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there
has been an official release, though.

casevh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread [EMAIL PROTECTED]
On Feb 23, 2:00 pm, [EMAIL PROTECTED] wrote:
> On Feb 23, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
>
> > > On Fri, 23 Feb 2007 09:52:06 -0600
>
> > > Larry Bates <[EMAIL PROTECTED]> wrote:
> > > > I quick search of Google turned up:
>
> > > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> > > >http://calcrpnpy.sourceforge.net/clnum.html
> > > >http://gmpy.sourceforge.net/
>
> > > Sorry that I did not point these out initially.
>
> > > + clnum seems to be slower and for speed may be compiled to wrap gmp so
> > > that it is just an additional layer between python and gmp .
>
> > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > cvs 10 months ago).
>
> I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.
>
> gmpy 1.04a compiles cleanly with the latest releases of Python and
> GMP, so I consider it stable.

Am I hallucinating? Didn't I see at least some version
of gmpy for Python 2.5 on SourceForge awhile back?
I distinctly remember thinking that I don't have to
direct people to your site, but SourceForge is not
showing anything beyond vesion 1.01 for Python 2.4.


>
> > Actually, gmpy is being maitained even if SourceForge isn't up to
> > date.
>
> > I got my gmpy 1.04a for Python 2.5 Windows binary from
>
> > 
>
> > I haven't used the rationals all that much, but been very
> > happy with them when I have.
>
> casevh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Martin Manns
On 23 Feb 2007 12:00:10 -0800
[EMAIL PROTECTED] wrote:
> 
> I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.
> 
> gmpy 1.04a compiles cleanly with the latest releases of Python and
> GMP, so I consider it stable.
> 
> >
> > Actually, gmpy is being maitained even if SourceForge isn't up to
> > date.
> >
> > I got my gmpy 1.04a for Python 2.5 Windows binary from
> >
> > 
> >
> > I haven't used the rationals all that much, but been very
> > happy with them when I have.
> >
> 
> casevh
> 

Thank you for all the replies.

I think that I am going to switch to gmpy.

Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread casevh
On Feb 23, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
>
> > On Fri, 23 Feb 2007 09:52:06 -0600
>
> > Larry Bates <[EMAIL PROTECTED]> wrote:
> > > I quick search of Google turned up:
>
> > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> > >http://calcrpnpy.sourceforge.net/clnum.html
> > >http://gmpy.sourceforge.net/
>
> > Sorry that I did not point these out initially.
>
> > + clnum seems to be slower and for speed may be compiled to wrap gmp so
> > that it is just an additional layer between python and gmp .
>
> > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > cvs 10 months ago).

I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
has not updated cvs with the fix.

gmpy 1.04a compiles cleanly with the latest releases of Python and
GMP, so I consider it stable.

>
> Actually, gmpy is being maitained even if SourceForge isn't up to
> date.
>
> I got my gmpy 1.04a for Python 2.5 Windows binary from
>
> 
>
> I haven't used the rationals all that much, but been very
> happy with them when I have.
>

casevh

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Martin Manns wrote:

> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

What CSV activities do you expect?  This package seems to be pretty
stable.  As long as there is no bug or incompatible changes in the
underlying library I would not expect changes to that package.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread [EMAIL PROTECTED]
On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
> On Fri, 23 Feb 2007 09:52:06 -0600
>
> Larry Bates <[EMAIL PROTECTED]> wrote:
> > I quick search of Google turned up:
>
> >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> >http://calcrpnpy.sourceforge.net/clnum.html
> >http://gmpy.sourceforge.net/
>
> Sorry that I did not point these out initially.
>
> + clnum seems to be slower and for speed may be compiled to wrap gmp so
> that it is just an additional layer between python and gmp .
>
> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

Actually, gmpy is being maitained even if SourceForge isn't up to
date.

I got my gmpy 1.04a for Python 2.5 Windows binary from



I haven't used the rationals all that much, but been very
happy with them when I have.


>
> + boost indeed is a quite nice C++ library. However, I fear that I
> would end up writing the python wrappers for operators (+ - * / min
> max cmp etc.) myself. I would like to avoid this since these operators
> should work correctly for any type (not just int and float) and I have
> little experience with verifying such generic code. The problems
> encountered in the mxNumber wrapper support this notion.
>
> Martin


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread bearophileHUGS
Martin Manns:
> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

I have used it on Py2.5, so it seems to work anyway, and it's fast
enough for my purposes. And probably soon some alex-shaped life will
show up elsewhere.

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers / alternatives to mxNumber

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 11:39:11 -0500
Martin Manns <[EMAIL PROTECTED]> wrote:

> + boost indeed is a quite nice C++ library. However, I fear that I
> would end up writing the python wrappers for operators (+ - * / min
> max cmp etc.) myself. I would like to avoid this since these operators
> should work correctly for any type (not just int and float) and I have
> little experience with verifying such generic code. The problems
> encountered in the mxNumber wrapper support this notion.


I just saw the pyboost-linux-0.1.1 package and tried it out.

ImportError: /home/mn/notes/libboost_python.so.1.34.0: undefined
symbol: PyUnicodeUCS4_FromEncodedObject

It seems to have problems with UCS2 compiled python.
Any robust rational wrapper out there?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 09:52:06 -0600
Larry Bates <[EMAIL PROTECTED]> wrote:
> I quick search of Google turned up:
> 
> http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg
> http://calcrpnpy.sourceforge.net/clnum.html
> http://gmpy.sourceforge.net/

Sorry that I did not point these out initially.

+ clnum seems to be slower and for speed may be compiled to wrap gmp so
that it is just an additional layer between python and gmp .

+ gmpy is looking pretty unmaintained (dead) to me (newest update of
cvs 10 months ago).

+ boost indeed is a quite nice C++ library. However, I fear that I
would end up writing the python wrappers for operators (+ - * / min
max cmp etc.) myself. I would like to avoid this since these operators
should work correctly for any type (not just int and float) and I have
little experience with verifying such generic code. The problems
encountered in the mxNumber wrapper support this notion.

Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread Larry Bates
Martin Manns wrote:
> Hi,
> 
> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
> 
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):
> 
> ---
> $ python
> Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
> [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from mx.Number import *
 a=Rational(0,1)
 a
> 0/1
 str(a)
> '0.0'
 b=-50
 b
> -50L
 a==b
> __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
> False
> ---
> 
> How do I get rid of these warnings?
> 
> Is there any rational number library around that
> 1) is comparably fast for large denominators
> 2) allows deriving types from Rationals without wrapping?
> 
> Regards
> 
> Martin
> 
> P.S. The respective mailing list does not like me, so that I try my
> luck here.

I quick search of Google turned up:

http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg
http://calcrpnpy.sourceforge.net/clnum.html
http://gmpy.sourceforge.net/

-Larry

-- 
http://mail.python.org/mailman/listinfo/python-list


Rational numbers

2007-02-23 Thread Martin Manns
Hi,

I am starting to use rationals and since I found no batteries included,
I tried out the mxNumber package.

However, I get strange warnings on comparison operations
(which however seem to yield correct results):

---
$ python
Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from mx.Number import *
>>> a=Rational(0,1)
>>> a
0/1
>>> str(a)
'0.0'
>>> b=-50
>>> b
-50L
>>> a==b
__main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
False
>>> 
---

How do I get rid of these warnings?

Is there any rational number library around that
1) is comparably fast for large denominators
2) allows deriving types from Rationals without wrapping?

Regards

Martin

P.S. The respective mailing list does not like me, so that I try my
luck here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fixed-point [was Re: Rational Numbers]

2007-01-14 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
|> 
|> Ok I will throw in a skewed ball at this point - use integer arithmetic,
|> and work in tenths of cents or pennies or whatever, and don't be too 
|> lazy to do your own print formatting...

If anyone is interested in doing this, here are a few notes on some of
the non-trivial aspects.  Please feel free if you want to contact me
for more information.

All numbers are held as (precision, value).  Precision is the number of
digits after the decimal point (a small, often constant, integer) and
the value is held as an integer.

It would be possible to have a separate subclass or context for every
precision (like Decimal), but that would be an unnecessary complication.

+, - and % return a precision that is the maximum of their input
precisions, and // returns a precision of 0.

* returns a precision that is the sum of its input precisions.

/ returns a floating-point number!

There is a divide function that takes a divisor, dividend and output
precision.  It also takes a rounding rule as an optional argument
(up, down, in, out, conventional nearest or IEEE 754R nearest).

There is a precision conversion function that takes a value and
output precision, and a rounding rule as an optional argument.

There is a conversion function that takes a string or floating-point
number and output precision, and a rounding rule as an optional
argument.  It raises an exception if a 1 ULP change in the floating-
point number would give a different answer; this is needed to make
certain operations reliable.

The default formatting does the obvious thing :-)

Er, that's about it 


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-14 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
|> 
|> > Financial calculations need decimal FIXED-point, with a precisely
|> > specified precision.  It is claimed that decimal FLOATING-point
|> > helps with providing that, but that claim is extremely dubious.
|> > I can explain the problem in as much detail as you want, but would
|> > very much rather not.
|> 
|> Ok I will throw in a skewed ball at this point - use integer arithmetic,
|> and work in tenths of cents or pennies or whatever, and don't be too 
|> lazy to do your own print formatting...

That's not a skewed ball - that's the traditional way of doing it on
systems that don't have fixed-point hardware (and sometimes even when
they do).  Yes, it's dead easy in a language (like Python) that allows
decent encapsulation.

The decimal floating-point brigade grossly exaggerate the difficulty of
doing that, in order to persuade people that their solution is better.
If they admitted the difficulties of using decimal floating-point, and
merely said "but, overall, we think it is a better solution", I would
disagree but say nothing.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-13 Thread Hendrik van Rooyen
From: "Nick Maclaren" <[EMAIL PROTECTED]> wrote:

> Financial calculations need decimal FIXED-point, with a precisely
> specified precision.  It is claimed that decimal FLOATING-point
> helps with providing that, but that claim is extremely dubious.
> I can explain the problem in as much detail as you want, but would
> very much rather not.

Ok I will throw in a skewed ball at this point - use integer arithmetic,
and work in tenths of cents or pennies or whatever, and don't be too 
lazy to do your own print formatting...

To represent $121.23 as a float is just asking for trouble when you
are trying to deal with something that can take a value like:

$123 456 789 012 345 678 901.07  - and you are worried about the 
seven cents for accounting purposes...

Remember that its not only money that is measured like that, but 
debt too...

-Hendrik

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-13 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Simon Brunning" <[EMAIL PROTECTED]> writes:
|> >
|> > Financial calculations need decimal FIXED-point, with a precisely
|> > specified precision.  It is claimed that decimal FLOATING-point
|> > helps with providing that, but that claim is extremely dubious.
|> > I can explain the problem in as much detail as you want, but would
|> > very much rather not.
|> 
|> Sorry, Nick, you might have to. ;-)
|> 
|> I'm not educated in these matters, so I'd genuinely like to know why
|> you say that. Not educated, but I do have some experience; I've used
|> both fixed and floating point Decimal types extensively, and I've
|> found floating types superior. More fiddly, certainly, 'cos you have
|> to explicitly round back down to the precision that you want when you
|> want. But explicit is better than implicit - the number of subtle
|> rounding bugs that I've had to fix 'cos someone didn't realise where
|> rounding was occurring is, uh, well, it happens from time to time. ;-)
|> 
|> What am I missing?

I will try to give a simple explanation, but I need to gloss over a
hell of a lot.  The precision is the number of digits after the
decimal point.

Financial calculations are defined in terms of decimal fixed-point,
with precisely specified precisions and rounding rules (though both
may vary with context, even in one expression).  Now, let's ignore
the arcana (especially as I know only a little of them) and note only
the following:

The traditional way of implementing fixed-point is as scaled integers,
and this is easy and reliable.  It is tricky if the USER is expected
to do it, but it is trivial to excapsulate.  Hell, even PLAN (the ICL
1900 assembler) did it!

If a number is calculated in floating-point, decimal or otherwise, and
needs any rounding, then it will NOT follow the right rules and no
reasonable amount of post-operation munging will enable it to do so.
Fixing up double rounding problems is inherently foul, so it is
ESSENTIAL that no operation is approximate.

In true fixed-point, the result of multiplication has a precision that
is the sum of the input precisions, and addition, subtraction and
remainder the maximum of the two.  Division is required to specify a
target precision and rounding rule.  Overflow is raised when the total
number of digits exceeds the space available.

A typical financial multiplication is a monetary amount multiplied by
a rate (say VAT, interest or a conversion rate).  That typically has
up to 5 digits, but there is no reason that it can't be more, and
it is possible that some calculations multiply several rates together.

When emulated in floating-point, the exception raised when the number
of digits exceeds the space available is Inexact (there is a slightly
different one for decimal, but the differences don't matter here).  So,
to get correct fixed-point flag handling, Inexact must be mapped to
Overflow.

Except for division, where there is no way to use the floating-point
primitive as a basis for the fixed-point one, so it has to be done by
hand, tediously and slowly.

But, in scientific (and current Python) usage, Inexact is always ignored
and Overflow is almost always an error.  If we do that mapping, it will
break ALL scientific code.  But, if we DON'T do that mapping, we will
abandon any attempt at getting reliable fixed-point overflow detection.
So you can't mix the two in the same program - which was one of the
main objectives of using decimal floating-point!

The counter-argument is that everyone will use 128-bit arithmetic for
all purposes.  Well, that is hooey, because it will cause MAJOR problems
for both the embedded people (logic, power and performance) and HPC
people (performance, mainly bandwidth).  Python could, probably.

However, that isn't what the Decimal module does anyway.  People will
specify more digits than they possibly need, not realising that they
need to specify many MORE if they are going to support multiplication.

Coming back to the start, is fixing that little lot up REALLY easier
than encapsulating scaled integers to give a proper fixed-point type?
I think that you will find that it is much harder!


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-13 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Steven D'Aprano <[EMAIL PROTECTED]> writes:
|> > 
|> > Some of the algebraic languages.  (2/3)^(1/5) is held as such and
|> > manipulated appropriately.
|> > 
|> > Yes, I know that's "cheating" :-)
|> 
|> I see your smiley, and I still don't understand. Why on earth would you
|> call it cheating for a language to have a data type that is suitable for
|> the data being used? Maybe it's a form of humour I don't get -- like
|> pointing at a car and saying "Look, a cow!".

Oh, because it's not a proper data type!  The data type is an expression,
and is held in a structured form, of which such powers may be one level.
This is better regarded as an optimisation of a common case than a true
data type.  Now, there MAY be such a language that supports such things
as a proper data type, but I don't know of one.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Steven D'Aprano
On Fri, 12 Jan 2007 17:15:56 +, Nick Maclaren wrote:

> In article <[EMAIL PROTECTED]>,
> Facundo Batista <[EMAIL PROTECTED]> writes:
> |> Noud Aldenhoven wrote:
> |> 
> |> > There are a (small) couple of other issues where rational numbers could 
> be
> |> > handy. That's because rational numbers are exact, irrational numbers (in
> |> > python) aren't. But these issues are probably too mathematical to be 
> used in
> |> 
> |> For the sake of me being less ignorant, could you please point me a
> |> language where irrational numbers are exact?
> 
> Some of the algebraic languages.  (2/3)^(1/5) is held as such and
> manipulated appropriately.
> 
> Yes, I know that's "cheating" :-)

I see your smiley, and I still don't understand. Why on earth would you
call it cheating for a language to have a data type that is suitable for
the data being used? Maybe it's a form of humour I don't get -- like
pointing at a car and saying "Look, a cow!".


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Steven D'Aprano
On Fri, 12 Jan 2007 20:07:04 +, Simon Brunning wrote:

> On 1/12/07, Thomas Ploch <[EMAIL PROTECTED]> wrote:
>> Do not forget:
>>
>> - Time
>> - Personal Data (like birthdays, age)
> 
> The datetime module has perfectly good classes for holding date and
> time values, and age sounds like an integer to me.

You've obviously never spoken to a small child who insists, absolutely
insists, that they aren't five years old, but "almost five and a half".

:)


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Simon Brunning
On 1/12/07, Thomas Ploch <[EMAIL PROTECTED]> wrote:
> Do not forget:
>
> - Time
> - Personal Data (like birthdays, age)

The datetime module has perfectly good classes for holding date and
time values, and age sounds like an integer to me.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Simon Brunning
On 12 Jan 2007 19:41:52 GMT, Nick Maclaren <[EMAIL PROTECTED]> wrote:
> Sigh.  I was hoping not to have that myth perpetrated again.
>
> Financial calculations need decimal FIXED-point, with a precisely
> specified precision.  It is claimed that decimal FLOATING-point
> helps with providing that, but that claim is extremely dubious.
> I can explain the problem in as much detail as you want, but would
> very much rather not.

Sorry, Nick, you might have to. ;-)

I'm not educated in these matters, so I'd genuinely like to know why
you say that. Not educated, but I do have some experience; I've used
both fixed and floating point Decimal types extensively, and I've
found floating types superior. More fiddly, certainly, 'cos you have
to explicitly round back down to the precision that you want when you
want. But explicit is better than implicit - the number of subtle
rounding bugs that I've had to fix 'cos someone didn't realise where
rounding was occurring is, uh, well, it happens from time to time. ;-)

What am I missing?

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Thomas Ploch
Simon Brunning schrieb:
> On 12 Jan 2007 15:55:39 GMT, Nick Maclaren <[EMAIL PROTECTED]> wrote:
>> In article <[EMAIL PROTECTED]>,
>> Carsten Haese <[EMAIL PROTECTED]> writes:
>> |> but there are more use
>> |> cases for Decimal than for Rational.
>>
>> That is dubious, but let's not start that one again.
> 
> Decimals are good for holding financial values. There's a whole lot of
> software out there that deals with money.
> 

Do not forget:

- Time
- Personal Data (like birthdays, age)

Thomas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Simon Brunning" <[EMAIL PROTECTED]> writes:
|>
|> > |> but there are more use
|> > |> cases for Decimal than for Rational.
|> >
|> > That is dubious, but let's not start that one again.
|> 
|> Decimals are good for holding financial values. There's a whole lot of
|> software out there that deals with money.

Sigh.  I was hoping not to have that myth perpetrated again.

Financial calculations need decimal FIXED-point, with a precisely
specified precision.  It is claimed that decimal FLOATING-point
helps with providing that, but that claim is extremely dubious.
I can explain the problem in as much detail as you want, but would
very much rather not.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Simon Brunning
On 12 Jan 2007 15:55:39 GMT, Nick Maclaren <[EMAIL PROTECTED]> wrote:
>
> In article <[EMAIL PROTECTED]>,
> Carsten Haese <[EMAIL PROTECTED]> writes:
> |> but there are more use
> |> cases for Decimal than for Rational.
>
> That is dubious, but let's not start that one again.

Decimals are good for holding financial values. There's a whole lot of
software out there that deals with money.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Noud Aldenhoven

On 1/12/07, Facundo Batista <[EMAIL PROTECTED]> wrote:


Noud Aldenhoven wrote:

> There are a (small) couple of other issues where rational numbers could
be
> handy. That's because rational numbers are exact, irrational numbers (in
> python) aren't. But these issues are probably too mathematical to be
used in

For the sake of me being less ignorant, could you please point me a
language where irrational numbers are exact?



I'm not sure, but I tought MAPLE could do it. This language has been
designed for solving mathimatical equotations (and other simulair stuf) and
could handle irrational numbers.
But ofcourse irrational numbers could never be exact when printed in an
g-notation (g > 1) system.

But now I mention that sentense is wrong... it should be: "That's because
rational numbers are exact, but in python they aren't most of the time."

To make irrational numbers exact in python should be, I think, more
unefficient than making rational numbers. But they could be very handy too
for calculating maths or physics equotations.

Regards,

Noud

--
<:3 )~
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rational Numbers

2007-01-12 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Facundo Batista <[EMAIL PROTECTED]> writes:
|> Noud Aldenhoven wrote:
|> 
|> > There are a (small) couple of other issues where rational numbers could be
|> > handy. That's because rational numbers are exact, irrational numbers (in
|> > python) aren't. But these issues are probably too mathematical to be used 
in
|> 
|> For the sake of me being less ignorant, could you please point me a
|> language where irrational numbers are exact?

Some of the algebraic languages.  (2/3)^(1/5) is held as such and
manipulated appropriately.

Yes, I know that's "cheating" :-)


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Facundo Batista
Noud Aldenhoven wrote:

> There are a (small) couple of other issues where rational numbers could be
> handy. That's because rational numbers are exact, irrational numbers (in
> python) aren't. But these issues are probably too mathematical to be used in

For the sake of me being less ignorant, could you please point me a
language where irrational numbers are exact?

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Carsten Haese <[EMAIL PROTECTED]> writes:
|> 
|> Ah, so now you're putting words in the BDFL's mouth. ;)
|> 
|> The pronouncement does say "The needs outlined in the rationale section
|> have been addressed to some extent by the acceptance of PEP 327 for
|> decimal arithmetic," but it doesn't say to which extent, and it
|> certainly doesn't claim that decimal arithmetic is a replacement for
|> rational arithmetic.

Eh?  If the needs are addressed to some extent, then to some extent
it is a replacement.

|> The sentence you're referring to is "There are excellent Rational
|> implementations [...]. Probably worth PEPping, not worth doing without
|> Decimal." I agree that this sentence is poorly worded, but I think it
|> means "Even if we had Rational, we'd still need Decimal" in the sense
|> that Rational is not an adequate replacement for Decimal.

Which would be justifiable, but is not what it said.  What it SAID is
what I said it said 

|> The bottom line is that there are use cases for both Rational and
|> Decimal, and neither one can replace the other,

So far, so good.  With reservations, I agree.

|> but there are more use
|> cases for Decimal than for Rational.

That is dubious, but let's not start that one again.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Carsten Haese
On Fri, 2007-01-12 at 15:05 +, Nick Maclaren wrote:
> In article <[EMAIL PROTECTED]>,
> Carsten Haese <[EMAIL PROTECTED]> writes:
> |> On Thu, 2007-01-11 at 23:47 +, Nick Maclaren wrote:
> |> > In article <[EMAIL PROTECTED]>,
> |> > Facundo Batista <[EMAIL PROTECTED]> writes:
> |> > |> Python does not have rational numbers.
> |> > |> 
> |> > |> There's a (rejected) PEP about this, PEP-239:
> |> > |> 
> |> > |>   http://www.python.org/dev/peps/pep-0239/
> |> > |> 
> |> > |> Maybe you also want to read the section "Why not rational?" of
> |> > |> PEP-327...
> |> > |> 
> |> > |>   http://www.python.org/dev/peps/pep-0327/#why-not-rational
> |> > 
> |> > Oh, God.  Decimal delusions again :-(
> |> > 
> |> > There are good arguments for not having a rational type, but the idea
> |> > that decimal floating-point is in any way a replacement is cuckoo.
> |> 
> |> You're putting words in Facundo's mouth. Facundo didn't say why we
> |> should read that section of PEP 327. I think he merely pointed to the
> |> slow performance of rational numbers that's explained in that section.
> |> (Facundo is the author of PEP 327, so I find it unlikely that he has
> |> delusions about what decimals can and can't do.)
> 
> You're putting words in MY mouth!  I didn't say that he did.  But I
> agree that my words could easily be read that way, so I apologise for
> any misunderstanding.
> [...]
> The BDFL Pronouncement rejecting PEP 239 does, even if it does qualify
> it by saying "to some extent".  And it was that PEP that I was primarily
> referring to in that remark.

Ah, so now you're putting words in the BDFL's mouth. ;)

The pronouncement does say "The needs outlined in the rationale section
have been addressed to some extent by the acceptance of PEP 327 for
decimal arithmetic," but it doesn't say to which extent, and it
certainly doesn't claim that decimal arithmetic is a replacement for
rational arithmetic.

> The "Why not rational?" section of PEP 327 quotes Alex Martelli as saying
> that Rational are not worth doing without Decimal, which makes no sense
> at all.  All it does is to plug Decimal for a purpose for which it is
> completely unsuited; not all rational numbers have denumerators that are
> powers of 10.

The sentence you're referring to is "There are excellent Rational
implementations [...]. Probably worth PEPping, not worth doing without
Decimal." I agree that this sentence is poorly worded, but I think it
means "Even if we had Rational, we'd still need Decimal" in the sense
that Rational is not an adequate replacement for Decimal.

The bottom line is that there are use cases for both Rational and
Decimal, and neither one can replace the other, but there are more use
cases for Decimal than for Rational.

-Carsten


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Carsten Haese <[EMAIL PROTECTED]> writes:
|> On Thu, 2007-01-11 at 23:47 +, Nick Maclaren wrote:
|> > In article <[EMAIL PROTECTED]>,
|> > Facundo Batista <[EMAIL PROTECTED]> writes:
|> > |> Noud Aldenhoven wrote:
|> > |> 
|> > |> > When I was programming in a mathematical project I began to wonder if 
python
|> > |> > supports rational numbers[1]. In a language like magma[2] it's not 
such a
|> > |> > problem. Does python supports something simular?
|> > |> 
|> > |> Python does not have rational numbers.
|> > |> 
|> > |> There's a (rejected) PEP about this, PEP-239:
|> > |> 
|> > |>   http://www.python.org/dev/peps/pep-0239/
|> > |> 
|> > |> Maybe you also want to read the section "Why not rational?" of
|> > |> PEP-327...
|> > |> 
|> > |>   http://www.python.org/dev/peps/pep-0327/#why-not-rational
|> > 
|> > Oh, God.  Decimal delusions again :-(
|> > 
|> > There are good arguments for not having a rational type, but the idea
|> > that decimal floating-point is in any way a replacement is cuckoo.
|> 
|> You're putting words in Facundo's mouth. Facundo didn't say why we
|> should read that section of PEP 327. I think he merely pointed to the
|> slow performance of rational numbers that's explained in that section.
|> (Facundo is the author of PEP 327, so I find it unlikely that he has
|> delusions about what decimals can and can't do.)

You're putting words in MY mouth!  I didn't say that he did.  But I
agree that my words could easily be read that way, so I apologise for
any misunderstanding.

|> It is true that decimal arithmetic is not a replacement for rational
|> arithmetic, but I don't see anybody on this thread or in PEP 327 stating
|> that it is.

Read them again, more carefully :-(

The BDFL Pronouncement rejecting PEP 239 does, even if it does qualify
it by saying "to some extent".  And it was that PEP that I was primarily
referring to in that remark.

The "Why not rational?" section of PEP 327 quotes Alex Martelli as saying
that Rational are not worth doing without Decimal, which makes no sense
at all.  All it does is to plug Decimal for a purpose for which it is
completely unsuited; not all rational numbers have denumerators that are
powers of 10.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-12 Thread Carsten Haese
On Thu, 2007-01-11 at 23:47 +, Nick Maclaren wrote:
> In article <[EMAIL PROTECTED]>,
> Facundo Batista <[EMAIL PROTECTED]> writes:
> |> Noud Aldenhoven wrote:
> |> 
> |> > When I was programming in a mathematical project I began to wonder if 
> python
> |> > supports rational numbers[1]. In a language like magma[2] it's not such a
> |> > problem. Does python supports something simular?
> |> 
> |> Python does not have rational numbers.
> |> 
> |> There's a (rejected) PEP about this, PEP-239:
> |> 
> |>   http://www.python.org/dev/peps/pep-0239/
> |> 
> |> Maybe you also want to read the section "Why not rational?" of
> |> PEP-327...
> |> 
> |>   http://www.python.org/dev/peps/pep-0327/#why-not-rational
> 
> Oh, God.  Decimal delusions again :-(
> 
> There are good arguments for not having a rational type, but the idea
> that decimal floating-point is in any way a replacement is cuckoo.

You're putting words in Facundo's mouth. Facundo didn't say why we
should read that section of PEP 327. I think he merely pointed to the
slow performance of rational numbers that's explained in that section.
(Facundo is the author of PEP 327, so I find it unlikely that he has
delusions about what decimals can and can't do.)

It is true that decimal arithmetic is not a replacement for rational
arithmetic, but I don't see anybody on this thread or in PEP 327 stating
that it is.

-Carsten


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-11 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Facundo Batista <[EMAIL PROTECTED]> writes:
|> Noud Aldenhoven wrote:
|> 
|> > When I was programming in a mathematical project I began to wonder if 
python
|> > supports rational numbers[1]. In a language like magma[2] it's not such a
|> > problem. Does python supports something simular?
|> 
|> Python does not have rational numbers.
|> 
|> There's a (rejected) PEP about this, PEP-239:
|> 
|>   http://www.python.org/dev/peps/pep-0239/
|> 
|> Maybe you also want to read the section "Why not rational?" of
|> PEP-327...
|> 
|>   http://www.python.org/dev/peps/pep-0327/#why-not-rational

Oh, God.  Decimal delusions again :-(

There are good arguments for not having a rational type, but the idea
that decimal floating-point is in any way a replacement is cuckoo.
The desirable properties that rationals and decimal arithmetic provide
are both genuine and are almost entirely different 

There are also perfectly good representations that don't have the
performance implications mentioned:  fixed and floating slash arithmetic.
They are mathematically quite interesting, and have some desirable
properties not shared by any floating-point format: e.g. if the result
is theoretically a rational with small numerator and denominator, then
they are very likely to return it.  I implemented fixed slash once, and
it is very easy to do - all it needs is a GCD routine - like rational,
it would be straightforward to add to Python as an extension type.


Regards,
Nick Maclaren.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-11 Thread Robert Kern
Noud Aldenhoven wrote:

> I'm a mathematician (in learning, with a bad feeling for English) and
> don't trust irrational numbers in programming languages.

You may want to look at SAGE. It provides a ton of good mathematical code.

  http://sage.scipy.org/sage/

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational Numbers

2007-01-11 Thread Noud Aldenhoven

On 1/11/07, Facundo Batista <[EMAIL PROTECTED]> wrote:


Python does not have rational numbers.



Ah, oke. Thank you, it seems I have enough information why they aren't
included in the core.

Question: Why do you say that it's a problem?


Well... Perhaps I word it wrong. It's not really a problem and if I need
rational numbers I'm smart enough to make an other algorithm that doesn't
need a build-in function for rational numbers.

I'm a mathematician (in learning, with a bad feeling for English) and don't
trust irrational numbers in programming languages.
It's, for example, in some cases it could be more efficient to compute an
irrational number with a rational numbers then using an advanced algorithm
of Euclides to compute the same.

To give a small example:

pi ~ 355/113
pi ~ 3.1415926

In my opinion the first one is better. But now I realise it's also the
slowest of the two implemented in python.

There are a (small) couple of other issues where rational numbers could be
handy. That's because rational numbers are exact, irrational numbers (in
python) aren't. But these issues are probably too mathematical to be used in
a programming language like python.

Regards,

Noud Aldenhoven

--
<:3 )~
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Rational Numbers

2007-01-11 Thread Facundo Batista
Noud Aldenhoven wrote:


> When I was programming in a mathematical project I began to wonder if python
> supports rational numbers[1]. In a language like magma[2] it's not such a
> problem. Does python supports something simular?

Python does not have rational numbers.

There's a (rejected) PEP about this, PEP-239:

  http://www.python.org/dev/peps/pep-0239/

Maybe you also want to read the section "Why not rational?" of
PEP-327...

  http://www.python.org/dev/peps/pep-0327/#why-not-rational

...and even take a look to gmpy:

  http://gmpy.sourceforge.net/


Question: Why do you say that it's a problem?

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


-- 
http://mail.python.org/mailman/listinfo/python-list


Rational Numbers

2007-01-11 Thread Noud Aldenhoven

Hello,

When I was programming in a mathematical project I began to wonder if python
supports rational numbers[1]. In a language like magma[2] it's not such a
problem. Does python supports something simular?

Greetings,

Noud Aldenhoven

--
<:3 )~

[1] http://en.wikipedia.org/wiki/Rational_number
[2] http://www.math.uiuc.edu/Software/magma/text283.html
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: rational numbers

2006-01-17 Thread Carsten Haese
On Tue, 2006-01-17 at 11:22, Paul Rubin wrote:
> Schüle Daniel <[EMAIL PROTECTED]> writes:
> > does anybody know modules which make rational numbers available?
> 
> Try gmpy.mpq (google for gmpy).
> 
> > and are there considerations to add them to the core, like
> > complex numbers (maybe in Python 3)
> 
> I don't think it's been discussed much.

Somebody must have discussed it. There is a rejected PEP for adding a
Rational type to python:

http://www.python.org/peps/pep-0239.html

-Carsten


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rational numbers

2006-01-17 Thread Paul Rubin
Schüle Daniel <[EMAIL PROTECTED]> writes:
> does anybody know modules which make rational numbers available?
> and are there considerations to add them to the core, like
> complex numbers (maybe in Python 3)

I think it's not likely.  In Scheme, (/ 5 2) is the rational number
5/2, while in current Python, 5/2 is the integer 2.  If Python got
native rationals, we'd expect something similar.  But it's been
publicly announced that in Python 3, 5/2 will be the floating point
number 2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: rational numbers

2006-01-17 Thread Paul Rubin
Schüle Daniel <[EMAIL PROTECTED]> writes:
> does anybody know modules which make rational numbers available?

Try gmpy.mpq (google for gmpy).

> and are there considerations to add them to the core, like
> complex numbers (maybe in Python 3)

I don't think it's been discussed much.
-- 
http://mail.python.org/mailman/listinfo/python-list


rational numbers

2006-01-17 Thread Schüle Daniel
Hello NG,

recently I was using Scheme and Ruby and was really nicely surprised
to find there support for the computing with rational numbers

for example this how it works in Ruby

mond:/pool/PROG/ruby # irb
irb(main):001:0>
irb(main):002:0* require "mathn"
=> true
irb(main):003:0> r = Rational(1,3)
=> 1/3
irb(main):004:0> p = Rational(1,5)
=> 1/5
irb(main):005:0> r+p
=> 8/15
irb(main):007:0> (r+p)**2
=> 64/225
irb(main):008:0>

does anybody know modules which make rational numbers available?
and are there considerations to add them to the core, like
complex numbers (maybe in Python 3)

Regards, Daniel

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-07 Thread [EMAIL PROTECTED]


Raymond Hettinger wrote:
> > > For a simple example, convert both 10247448370872321 and
> > > 10247448370872319 from base ten to 4 digits of hex.  The calculations
> > > need to be carried out to 15 places of hex (or 17 places of decimal)
> > > just to determine whether the fourth hex digit is a 7 or 8:
> > >
> > > >>> hex(10247448370872321)
> > > '0x246801L'
> > > >>> hex(10247448370872319)
> > > '0x2467ffL'
> >
> > I don't understand your simple example.
> >
> > log(10)/log(16) = 0.83048202372184058696757985737235
> >
> > Multiplying by the number of decimal digits (17) gives
> >
> > 14.11819440327128997844885757533
> >
> > Rounding up to an integer digit count, we need need 15 hex digits.
> > Isn't that exactly what you concluded? Where does that 4 hex digit
> > stuff come from?
>
> It is part of the OP's problem spec.  Given a number x (which may be a
> decimal, float, long integer, or rational), a base b, and a desired
> precision p, compute the conversion to p-digits:
>
>   >>> convert(x=10247448370872319L, b=16, p=4)
>   '246800'

But you haven't explained why you are using p=4. The OP's problem
is that he's doing convert(x=10247448370872319L, b=16, p=17).
So of course it's going to be wrong because base 16 numbers are
bigger than base 10 numbers. By trying to use the same precision
with different bases, he's asking for more precision in the base 17
number than what exists in the base 10 number.

>
> He wanted to know what decimal precision he needed to set to make the
> conversion accurate to the last place.  The required precision for
> intermediate calculations depends on how close x is to a representable
> value in the target base.  The 16 digits are not known a priori since x
> may be a rational, float, or decimal.  For instance, an internal
> precision of 17 digits would also be needed for other nearby values of
> x:
>
>   >>> convert(x=Decimal("10247448370872319.1", b=16, p=4)
>   '246800'

Now your base 10 number has 26 digits. So shouldn't your convert be
using p=22?

>
> The number 17 does not just pop-out of a simple logarithm.

It most certainly does

>>> print floor(math.log10(10247448370872319)) + 1
17.0


> How many
> internal digits of precision do you need for convert(math.pi, b=16,
> p=5)?

I think I would need 7.

Because
>>> print math.log(16)/math.log(10)*5
6.02059991328


>>> from gmpy import *
>>> import math
>>> print math.pi
3.14159265359

Using math.pi

>>> print fdigits(math.pi,16,5)
[EMAIL PROTECTED]

Using only seven digits

>>> print fdigits(mpf("3.141593"),16,5)
[EMAIL PROTECTED]

I don't see any problem.

> If the result falls closely between reprentable values, the OP
> may need to set his "magic number" to something larger than you would
> have predicted.
>
> If you want insight into why the OP's problem statement is deeper than
> it appears, then ponder the mystery of why the following returns False:
>
>   >>> x = 554459760520464551937111727196883414687442277344893869152167
>   >>> float(x) == float(str(x))
>   False

No big mystery. Isn't that why they added the Decimal module?

>
> Hint, the two different underlying routines are trying to compute,
> convert(x, b=2, p=53), without the benefit of arbitrary precision
> arithmetic.

Yep, sure is nice to have that.

>>> x = mpz(554459760520464551937111727196883414687442277344893869152167)
>>> float(x)==float(str(x))
True


> 
> 
> Raymond

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-06 Thread Raymond Hettinger
> > For a simple example, convert both 10247448370872321 and
> > 10247448370872319 from base ten to 4 digits of hex.  The calculations
> > need to be carried out to 15 places of hex (or 17 places of decimal)
> > just to determine whether the fourth hex digit is a 7 or 8:
> >
> > >>> hex(10247448370872321)
> > '0x246801L'
> > >>> hex(10247448370872319)
> > '0x2467ffL'
>
> I don't understand your simple example.
>
> log(10)/log(16) = 0.83048202372184058696757985737235
>
> Multiplying by the number of decimal digits (17) gives
>
> 14.11819440327128997844885757533
>
> Rounding up to an integer digit count, we need need 15 hex digits.
> Isn't that exactly what you concluded? Where does that 4 hex digit
> stuff come from?

It is part of the OP's problem spec.  Given a number x (which may be a
decimal, float, long integer, or rational), a base b, and a desired
precision p, compute the conversion to p-digits:

  >>> convert(x=10247448370872319L, b=16, p=4)
  '246800'

He wanted to know what decimal precision he needed to set to make the
conversion accurate to the last place.  The required precision for
intermediate calculations depends on how close x is to a representable
value in the target base.  The 16 digits are not known a priori since x
may be a rational, float, or decimal.  For instance, an internal
precision of 17 digits would also be needed for other nearby values of
x:

  >>> convert(x=Decimal("10247448370872319.1", b=16, p=4)
  '246800'

The number 17 does not just pop-out of a simple logarithm.  How many
internal digits of precision do you need for convert(math.pi, b=16,
p=5)?  If the result falls closely between reprentable values, the OP
may need to set his "magic number" to something larger than you would
have predicted.

If you want insight into why the OP's problem statement is deeper than
it appears, then ponder the mystery of why the following returns False:

  >>> x = 554459760520464551937111727196883414687442277344893869152167
  >>> float(x) == float(str(x))
  False

Hint, the two different underlying routines are trying to compute,
convert(x, b=2, p=53), without the benefit of arbitrary precision
arithmetic.


Raymond

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-06 Thread [EMAIL PROTECTED]


Raymond Hettinger wrote:
> [Terry Hancock]
> > > Needless to say, the conventional floating point numbers in Python
> > > are actually stored as *binary*, which is why there is a "decimal"
> > > module (which is new).
> > >
> > > If you're going to be converting between bases anyway, it probably
> > > makes little difference whether you are using the decimal module
> > > or not, of course.  You'll have the same problems the conventional
> > > float numbers do.
>
> Not really.  floats won't do because they may not have sufficient
> precision to differentiate rational values falling close the split
> between representable values in a given base.  The decimal module
> offers arbitrarily large precision for making sure the error-term is
> small enough to not make a difference.
>
>
>
> [Brian van den Broek]
> > Thanks. mensanator provided the actual formula for my case. I had a
> > "magic number" in my code by which I multiplied my desired level of
> > "number of places in the representation" to obtain the value for
> > decimal.getcontext.prec.
> >
> > mensanator wrote:
> >
> > > The value you want for x is log(17)/log(10) =
> > > 1.2304489213782739285401698943283
> >
> > where x was my "magic number". I've not had a chance to think it
> > through yet, but I feel confident that given the formula, I'll be able
> > to work out *why* that is the formula I need.
>
> That "formula" just gives a starting point estimate.  The required
> decimal precision may be much higher.  If the rational falls very close
> to the half-way point between two representable numbers, the
> calculation needs to be retried with increased precision until the
> split-point is definitive (when the error-term becomes less than the
> distance to the next representable value).
>
> For a simple example, convert both 10247448370872321 and
> 10247448370872319 from base ten to 4 digits of hex.  The calculations
> need to be carried out to 15 places of hex (or 17 places of decimal)
> just to determine whether the fourth hex digit is a 7 or 8:
>
> >>> hex(10247448370872321)
> '0x246801L'
> >>> hex(10247448370872319)
> '0x2467ffL'

I don't understand your simple example.

log(10)/log(16) = 0.83048202372184058696757985737235

Multiplying by the number of decimal digits (17) gives

14.11819440327128997844885757533

Rounding up to an integer digit count, we need need 15 hex digits.
Isn't that exactly what you concluded? Where does that 4 hex digit
stuff come from?

>
> For an example of using decimal with iteratively increasing precision,
> see the dsum() recipe at
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 .
> 
> 
> Raymond

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-06 Thread Raymond Hettinger
[Terry Hancock]
> > Needless to say, the conventional floating point numbers in Python
> > are actually stored as *binary*, which is why there is a "decimal"
> > module (which is new).
> >
> > If you're going to be converting between bases anyway, it probably
> > makes little difference whether you are using the decimal module
> > or not, of course.  You'll have the same problems the conventional
> > float numbers do.

Not really.  floats won't do because they may not have sufficient
precision to differentiate rational values falling close the split
between representable values in a given base.  The decimal module
offers arbitrarily large precision for making sure the error-term is
small enough to not make a difference.



[Brian van den Broek]
> Thanks. mensanator provided the actual formula for my case. I had a
> "magic number" in my code by which I multiplied my desired level of
> "number of places in the representation" to obtain the value for
> decimal.getcontext.prec.
>
> mensanator wrote:
>
> > The value you want for x is log(17)/log(10) =
> > 1.2304489213782739285401698943283
>
> where x was my "magic number". I've not had a chance to think it
> through yet, but I feel confident that given the formula, I'll be able
> to work out *why* that is the formula I need.

That "formula" just gives a starting point estimate.  The required
decimal precision may be much higher.  If the rational falls very close
to the half-way point between two representable numbers, the
calculation needs to be retried with increased precision until the
split-point is definitive (when the error-term becomes less than the
distance to the next representable value).

For a simple example, convert both 10247448370872321 and
10247448370872319 from base ten to 4 digits of hex.  The calculations
need to be carried out to 15 places of hex (or 17 places of decimal)
just to determine whether the fourth hex digit is a 7 or 8:

>>> hex(10247448370872321)
'0x246801L'
>>> hex(10247448370872319)
'0x2467ffL'

For an example of using decimal with iteratively increasing precision,
see the dsum() recipe at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090 .


Raymond

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread Dan Bishop
Brian van den Broek wrote:
> Hi all,
>
> I guess it is more of a maths question than a programming one, but it
> involves use of the decimal module, so here goes:
>
> As a self-directed learning exercise I've been working on a script to
> convert numbers to arbitrary bases. It aims to take any of whole
> numbers (python ints, longs, or Decimals), rational numbers (n / m n,
> m whole) and floating points (the best I can do for reals), and
> convert them to any base between 2 and 36, to desired precision.
...
> I've discovered empirically that I have to set getcontext.prec = 99 or
> greater (i.e. x >= 1.2375) to get
> 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C
>
> (I do feel safe in assuming that is the right answer. :-)

And you are correct.

~$ repdigits 345/756 17
0.(7CF0CA)

(That's from a script I wrote a couple of years ago.  For your next
self-directed learning exercise, you could get your program to produce
that output :-)

Anyhow, if you need such precise precision, perhaps you should consider
doing an exact calculation, with rational numbers.





"""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')
   # Store the fraction in reduced form as _n/_d
   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)):
 

Re: precision problems in base conversion of rational numbers

2005-07-05 Thread Brian van den Broek
Terry Hancock said unto the world upon 05/07/2005 11:49:
> On Monday 04 July 2005 06:11 am, Brian van den Broek wrote:
> 
>>As a self-directed learning exercise I've been working on a script to 
>>convert numbers to arbitrary bases. It aims to take any of whole 
>>numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
>>m whole) and floating points (the best I can do for reals), and 
>>convert them to any base between 2 and 36, to desired precision.

Thanks to Terry and mensanator for the replies.

To consolidate, I respond to Terry in-line and then add some response 
to mensanator at the end.


> Interesting, I'd like to see that.

I'd like it to be seen :-)  I will soon send my current version in a 
private email.


>>I'm pretty close but I know I am not handling the precision quite 
>>right. Nothing other than understanding hangs on it, but, that's 
>>enough :-)
> 
> 
> Okay.  You do understand that many numbers that can be exactly
> represented in one base cannot be in another?

Indeed. The original impetus for writing this was to substantiate my 
claim in an off-list conversation that whether a given rational had a 
repeating or terminating expansion was a function of the base of 
representation. In particular, that 1 / n in base n is 0.1


> E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating
> decimal: 0.333  And of course, there are infinitely many
> other examples.

The exact example I used in my off-list exchange :-)
(No "great minds" claim, sadly, as it is the natural example.)





> Needless to say, the conventional floating point numbers in Python
> are actually stored as *binary*, which is why there is a "decimal"
> module (which is new).
> 
> If you're going to be converting between bases anyway, it probably
> makes little difference whether you are using the decimal module
> or not, of course.  You'll have the same problems the conventional
> float numbers do.

It may be a function of the algorithm I picked, but I am almost 
certain that I switched to employing Decimals after finding a 
substantial inaccuracy with a purely float logic. I will likely get 
around to switching back to floats late tonight to confirm my 
recollection.


> Getting back to your precision problem: I bet if you simply
> evaluate the error term as I have above, and then convert *that* into
> your base of choice, you will be able to tell how many places are
> correct in the conversion.
> 
> That is to, say, stop think about "number of places" and instead
> think about "representation error".  That number is a real property
> of the data which can be represented in any base.  Then you can
> convert it to number of places in the representation process.

A useful "cognitive correction", thanks :-)


> e.g. 0.05 has 6 places behind the zero in decimal, how many
> does base3(0.05)? --- that's the accuracy of the statement
> 
> 0.3 base10 ~= 0.1 base3 +- base3(0.05 base10)
> 
> Roughly, we know that 0.05 = 10^-5 / 2.  The same term
> in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved
> using logarithms, but I'll "leave that as an excercise for the reader",
> because I'm too lazy to go look it up, and I've forgotten the
> details. ;-)

Thanks. mensanator provided the actual formula for my case. I had a 
"magic number" in my code by which I multiplied my desired level of 
"number of places in the representation" to obtain the value for 
decimal.getcontext.prec.

mensanator wrote:

> The value you want for x is log(17)/log(10) =
> 1.2304489213782739285401698943283

where x was my "magic number". I've not had a chance to think it 
through yet, but I feel confident that given the formula, I'll be able 
to work out *why* that is the formula I need.

So, thanks for that, too.

mensanator also pointed out an inaccuracy in my posted example. I had 
345 / 756 represented in base 17 to 80 digits, and came up with a 
repeating expansion. It was pointed out that I should have rounded up 
the last 'digit' ['17-it' ? :-) ]. Indeed. I'd been concentrating on 
getting the conversion logic right before adding logic to deal with 
rounding and should have mentioned my result was not a rounded one, 
but merely a truncation of the infinite expansion. Thanks for the 
correction / reminder to add the logic.

> I hope this is helpful, though,
> Terry

Indeed, both your's and mensanator's. Thanks to both. Best to all,

Brian vdB


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread [EMAIL PROTECTED]


Brian van den Broek wrote:
> Hi all,
>
> I guess it is more of a maths question than a programming one, but it
> involves use of the decimal module, so here goes:
>
> As a self-directed learning exercise I've been working on a script to
> convert numbers to arbitrary bases. It aims to take any of whole
> numbers (python ints, longs, or Decimals), rational numbers (n / m n,
> m whole) and floating points (the best I can do for reals), and
> convert them to any base between 2 and 36, to desired precision.
>
> I'm pretty close but I know I am not handling the precision quite
> right. Nothing other than understanding hangs on it, but, that's
> enough :-)
>
> To do all this I'm using the decimal module (for the first time) and
> I've been setting the precision with
>
> decimal.getcontext().prec = max(getcontext().prec,
>  x * self.precision )
>
> This is in my class's __init__ method before I convert every number to
> Decimal type and self.precision is at this point an int passed.
>
> The first term is to be sure not to reduce precision anywhere else. In
> the last term I'd started off with x = 1, and that works well enough
> for "small" cases (i.e. cases where I demanded a relatively low degree
> of precision in the output).
>
> I've no idea how to work out what x should be in general. (I realize
> the answer may be a function of my choice of algorithm. If it is
> needed, I'm happy to extract the relevant chunks of code in a
> follow-up -- this is long already.)
>
> For getcontext.prec = 80 (i.e x = 1) when I work out 345 / 756 in base
> 17 to 80 places (i.e. self.precision = 80) I get:
>
>  >>> print Rational_in_base_n(345, 756, 17, 80)
> 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0D5C1G603999179EB
>
> (Rational_in_base_n(numerator, denominator, base, precision) is the
> rational specific subclass. When I convert the result back to decimal
> notation by hand it agrees with the correct answer to as many places
> as I cared to check.)
>
> I've discovered empirically that I have to set getcontext.prec = 99 or
> greater (i.e. x >= 1.2375) to get

The value you want for x is log(17)/log(10) =
1.2304489213782739285401698943283

Multiplied by 80 gives you 98.435913710261914283213591546267, but you
can't
have a fraction of a digit, so round up to 99 (giving x=1.235).

> 0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C
>
> (I do feel safe in assuming that is the right answer. :-)

It's not. The last digit should be "D".

This is how the GMPY module handles it:

>>> from gmpy import *

>>> # Create an unlimited precision rational.
>>> r = mpq(345,756)

>>> # Convert rational to floating point with 300 bits precision.
>>> # GMPY default precision is based on the nature of the rational
>>> # but can be specified. Note that prcision is in bits, not digits.
>>> f = mpf(r,300)
>>> print f
0.45634920634920634920634920634920634920634920634920634920634920634920634920634920634920634920634921

>>> # Convert the floating point to base 17.
>>> # Note that it has been correctly rounded up, so last digit is 'd'.
>>> print fdigits(f,17)
[EMAIL PROTECTED]


>
> How would I go about working out what degree of precision for the
> decimal module's context is needed to get n 'digits' of precision in
> an expression of base m in general? (I've no formal training in Comp
> Sci, nor in the relevant branches of mathematics.)
> 
> Thanks and best,
> 
> Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: precision problems in base conversion of rational numbers

2005-07-05 Thread Terry Hancock
On Monday 04 July 2005 06:11 am, Brian van den Broek wrote:
> As a self-directed learning exercise I've been working on a script to 
> convert numbers to arbitrary bases. It aims to take any of whole 
> numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
> m whole) and floating points (the best I can do for reals), and 
> convert them to any base between 2 and 36, to desired precision.

Interesting, I'd like to see that.

> I'm pretty close but I know I am not handling the precision quite 
> right. Nothing other than understanding hangs on it, but, that's 
> enough :-)

Okay.  You do understand that many numbers that can be exactly
represented in one base cannot be in another?

E.g. in base 3, one-third is 0.1, but in base 10, it's a repeating
decimal: 0.333  And of course, there are infinitely many
other examples.

So what you're really doing is trying to make sure that you don't
*lose* precision in the conversion, *except* due to this point. I.e.
you want to do the best you can do.

I would say that if you have a number of places past the decimal
point, that can be interpreted as the error of the representation:

1/3   ~=  0.3 base10 +- 0.05

Needless to say, the conventional floating point numbers in Python
are actually stored as *binary*, which is why there is a "decimal"
module (which is new).

If you're going to be converting between bases anyway, it probably
makes little difference whether you are using the decimal module
or not, of course.  You'll have the same problems the conventional
float numbers do.

Getting back to your precision problem: I bet if you simply
evaluate the error term as I have above, and then convert *that* into
your base of choice, you will be able to tell how many places are
correct in the conversion.

That is to, say, stop think about "number of places" and instead
think about "representation error".  That number is a real property
of the data which can be represented in any base.  Then you can
convert it to number of places in the representation process.

e.g. 0.05 has 6 places behind the zero in decimal, how many
does base3(0.05)? --- that's the accuracy of the statement

0.3 base10 ~= 0.1 base3 +- base3(0.05 base10)

Roughly, we know that 0.05 = 10^-5 / 2.  The same term
in base 3 will be 3^-x/2 = 10^5/2 places, which can be solved
using logarithms, but I'll "leave that as an excercise for the reader",
because I'm too lazy to go look it up, and I've forgotten the
details. ;-)

I hope this is helpful, though,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

-- 
http://mail.python.org/mailman/listinfo/python-list


precision problems in base conversion of rational numbers

2005-07-04 Thread Brian van den Broek
Hi all,

I guess it is more of a maths question than a programming one, but it 
involves use of the decimal module, so here goes:

As a self-directed learning exercise I've been working on a script to 
convert numbers to arbitrary bases. It aims to take any of whole 
numbers (python ints, longs, or Decimals), rational numbers (n / m n, 
m whole) and floating points (the best I can do for reals), and 
convert them to any base between 2 and 36, to desired precision.

I'm pretty close but I know I am not handling the precision quite 
right. Nothing other than understanding hangs on it, but, that's 
enough :-)

To do all this I'm using the decimal module (for the first time) and 
I've been setting the precision with

decimal.getcontext().prec = max(getcontext().prec,
 x * self.precision )

This is in my class's __init__ method before I convert every number to 
Decimal type and self.precision is at this point an int passed.

The first term is to be sure not to reduce precision anywhere else. In 
the last term I'd started off with x = 1, and that works well enough 
for "small" cases (i.e. cases where I demanded a relatively low degree 
of precision in the output).

I've no idea how to work out what x should be in general. (I realize 
the answer may be a function of my choice of algorithm. If it is 
needed, I'm happy to extract the relevant chunks of code in a 
follow-up -- this is long already.)

For getcontext.prec = 80 (i.e x = 1) when I work out 345 / 756 in base 
17 to 80 places (i.e. self.precision = 80) I get:

 >>> print Rational_in_base_n(345, 756, 17, 80)
0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0D5C1G603999179EB

(Rational_in_base_n(numerator, denominator, base, precision) is the 
rational specific subclass. When I convert the result back to decimal 
notation by hand it agrees with the correct answer to as many places 
as I cared to check.)

I've discovered empirically that I have to set getcontext.prec = 99 or 
greater (i.e. x >= 1.2375) to get
0.7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7CF0CA7C

(I do feel safe in assuming that is the right answer. :-)

How would I go about working out what degree of precision for the 
decimal module's context is needed to get n 'digits' of precision in 
an expression of base m in general? (I've no formal training in Comp 
Sci, nor in the relevant branches of mathematics.)

Thanks and best,

Brian vdB

-- 
http://mail.python.org/mailman/listinfo/python-list