Floating-point glitches with the math module. Bug? Or am I missing something?
Jeff Epler
jepler at unpythonic.net
Mon Sep 20 20:03:57 EDT 2004
If it's any consolation, I get similar problems in C. Whenever Python
does floating point math, it thinly wraps your C compiler's math
library.
$ cat > metzler.c <<EOF
> #include <math.h>
>
> double x, y, z;
> double cos_gamma3, gamma3;
>
> int main(void) {
> x = 0.999999;
> y = 0.999997;
> z = 1e-08;
>
> cos_gamma3 = cos(x - y) - sin(x)*sin(y)*(1.0 - cos(z));
> gamma3 = acos(cos_gamma3);
>
> printf("This shold be positive: %g\n", gamma3 - fabs(x-y));
> return 0;
> }
> EOF
$ gcc metzler.c -lm -o metzler
$ ./metzler
This shold be positive: -2.21218e-11
acos(cos(d)) for small d gives fairly large errors on my system:
>>> d = .999999 - .9999977
>>> acos(cos(d)), d
(1.2999928800133351e-06,
1.2999999999818712e-06)
>>> # ^ First difference here
a half dozen correct digits isn't great, but it's all my platform's trig
functions seem to give me. And you're trying to make a silk purse out
of a sow's ear...
Incidentally, the second part of your expression goes to 0 here, with
the given values:
>>> cos(z) == 1.0
True
>>> sin(x)*sin(y)*(1-cos(z))
0.0
>>> _ == 0
True
Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20040920/7cc2be45/attachment.sig>
More information about the Python-list
mailing list