[Greg Ewing <greg.ew...@canterbury.ac.nz>] > So can you elaborate on how you use variable precision?
Numeric programmers frequently want this. An extreme example is in function `collision_stats()` in your Python distribution's Lib/test/support/__init__.py. This needs to compute the variance of a distribution for which we only have a mathematical derivation. That's exact "in theory", but the expression suffers massive cancellation in native floating point. In context, it would deliver 100% gibberish results. The comments note that it's easy to use rationals (fractions.Fraction) instead - but doing so in context would require multi-million bit integer arithmetic and be unbearably slow (voice of experience there - that's how I wrote it at first, and wondered why test_tuple never finished). `decimal` to the rescue! It's fast and highly accurate now. It just sets the context to use a number of decimal digits twice the number of bits in the crucial input. There's still utterly massive cancellation, but it doesn't matter: there are enough "extra" decimal digits that losing mounds of the leading digits to cancellation doesn't matter to the result. Base 10 is irrelevant to this - base 2 would work fine too. It's the ability to greatly boost precision that matters. BTW, like any sane isolated code that messes with the context, it does so locally: with decimal.localcontext() as ctx: bits = n.bit_length() * 2 # bits in n**2 # At least that many bits will likely cancel out. # Use that many decimal digits instead. ctx.prec = max(bits, 30) I know of no other way to get this done with sane effort in core Python; and, e.g., we can't reasonably require installing the `mpmath` extension just to run Python's standard test suite. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/M3ORKFUKLSSGD7XICLTEE7UZEIYTWGMX/ Code of Conduct: http://python.org/psf/codeofconduct/