math module for Decimals

Fredrik Johansson fredrik.johansson at gmail.com
Tue Jan 6 16:48:54 EST 2009


On Jan 6, 8:29 pm, Mark Dickinson <dicki... at gmail.com> wrote:

> Note that it's still subject to the same limitations as anything
> else for trig_function(really huge argument), of course:
>
> >>> import mpmath
> >>> mpmath.cos(mpmath.mpf('1e999999999'))
>
> [... still waiting for a result 30 minutes later ...]
>
> (not a criticism of mpmath:  just a demonstration that this
> really is pretty much unavoidable).

Indeed. That's asking for 1 billion digits of pi.

(I feel that I need to point out that mpmath really does go out of its
way to make ridiculous things like that work, though. It uses a very
fast algorithm to compute pi, faster than MPFR even. Assuming gmpy is
installed on the system and enough RAM, cos('1e999999999') should
finish in about 10^5 seconds = 1 day (based on extrapolation on my
computer). You just weren't patient enough :-)

> Out of curiosity, what sort of guarantees does mpmath give on
> error bounds?  It looks like it aims for 'almost correctly
> rounded';  i.e., error < 0.500...001 ulps.

Sort of; there are different standards of rigor. The basic arithmetic
operations are correctly rounded. The elementary functions are 'almost
correctly rounded' in the sense you described (subject to the usual
bug disclaimer); they are also correctly rounded around some zeros and
poles (e.g. sin(x) for sufficiently small x properly rounds to x or x*
(1-eps) if upward/downward rounding is used).

Some other functions like erf and gamma are 'almost correctly rounded'
for real arguments, but currently no attempt is made to correct for
cancellations in real/imaginary parts (this problem is mostly avoided
for elementary functions by decomposition into real-valued functions
like cos(a+b*i) = cos(a)*cosh(b)-sin(a)*sinh(b)*i). Finally, some
"higher" functions are computed more naively and can easily be forced
to lose accuracy by finding large arguments that correspond to small
function values.

It would indeed be nice to support correct rounding for at least the
elementary transcendental functions in the future. One advantage of
arbitrary precision is that the user can compensate for rounding
errors very easily by just increasing the working precision, but
ideally that shouldn't be necessary for atomic operations.

> Here's one place in mpmath where it looks as though more
> internal precision is needed (with default settings: 53-bit
> precision, etc.)
>
> >>> mpmath.log(mpmath.mpc(0.6, 0.8))
>
> mpc(real='0.0', imag='0.9272952180016123')
>
> Shouldn't the real part here be something like:
>
> 2.2204460492503132e-17
>
> instead of 0.0?

That's certainly a bug; it should be fixed soon.

Fredrik



More information about the Python-list mailing list