Floating-point glitches with the math module. Bug? Or am I missing something?

Paul Rubin http
Tue Sep 21 01:18:38 EDT 2004


Chris Metzler <cmetzler at speakeasy.snip-me.net> writes:
> >>> print math.acos(math.cos(2e-8))
> 2.10734242554e-08
> 
> 5% error at 2e-8 is awful; and anything below 1.1e-8 is 0, pretty much.  

I don't know if you can expect much better.  For small x, cos(x) is
approx. 1-x^2/2, so cos(2e-8) is about 1-(2e-16), which is pushing the
precision of an IEEE double.  It's not a library error; you're
reaching the limits of what the machine arithmetic can do.

> I can't find a module in the Library Reference that provides
> higher-precision functions.  Is there one around?

I guess you could use gmpy and some infinite series, or there may be a
way to recompile Python to use 80-bit extended floats if your hardware
supports them (the x86 does).  However, the best approach is to
arrange your calculation to not lose precision so easily.  Any
numerical analysis book spends a lot of time discussing how to do that.



More information about the Python-list mailing list