Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #111484
| From | Random832 <random832@fastmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: math.frexp |
| Date | 2016-07-15 14:28 -0400 |
| Message-ID | <mailman.24.1468607289.2307.python-list@python.org> (permalink) |
| References | <5788cb76$0$1599$c3e8da3$5496439d@news.astraweb.com> <CAPTjJmq=wGopxP_49b6CEjU-N8YbyGeWF85YW+5pe+T_Lsycpg@mail.gmail.com> <mailman.16.1468583297.2307.python-list@python.org> <5789101c$0$1615$c3e8da3$5496439d@news.astraweb.com> <1468607285.2744204.667500217.193B8D54@webmail.messagingengine.com> |
On Fri, Jul 15, 2016, at 12:32, Steven D'Aprano wrote:
> I can take the geometric mean of:
>
> [2.0**900, 2.0**920, 2.0**960, 2.0**980, 2.0**990]
>
> and get to within a relative error of 1e-14 of the correct answer,
> 2**950:
>
> py> geometric_mean([2.0**900, 2.0**920, 2.0**960, 2.0**980, 2.0**990])
> 9.516908214257811e+285
> py> 2.0**950
> 9.516908214257812e+285
>
> Here's one that's exact:
>
> py> geometric_mean([2e300, 4e300, 8e300, 16e300, 32e300])
> 8e+300
My own attempt gave an exact result for both test cases.
from math import frexp as _frexp, ldexp
def frexp(x):
if type(x) is tuple:
m, e1 = x
m, e2 = _frexp(m)
return m, e1 + e2
else:
return _frexp(x)
def _mul(a, b):
ma, ea = frexp(a)
mb, eb = frexp(b)
return frexp((ma * mb, ea + eb))
def _product(values):
return reduce(_mul, values)
def geometric_mean(values):
n = len(values)
pm, pe = _product(values)
me, re = divmod(pe, n)
pm = ldexp(pm, re)
return ldexp(pm**(1./n), me)
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
math.frexp Steven D'Aprano <steve@pearwood.info> - 2016-07-15 21:39 +1000
Re: math.frexp Chris Angelico <rosuav@gmail.com> - 2016-07-15 21:48 +1000
Re: math.frexp Steven D'Aprano <steve@pearwood.info> - 2016-07-16 02:32 +1000
Re: math.frexp Chris Angelico <rosuav@gmail.com> - 2016-07-16 02:44 +1000
Re: math.frexp Random832 <random832@fastmail.com> - 2016-07-15 14:28 -0400
Re: math.frexp Paul Rubin <no.email@nospam.invalid> - 2016-07-15 13:24 -0700
Re: math.frexp Steven D'Aprano <steve@pearwood.info> - 2016-07-16 20:21 +1000
Re: math.frexp Paul Rubin <no.email@nospam.invalid> - 2016-07-16 12:49 -0700
Re: math.frexp Nobody <nobody@nowhere.invalid> - 2016-07-15 17:39 +0100
Re: math.frexp Vlastimil Brom <vlastimil.brom@gmail.com> - 2016-07-17 01:18 +0200
csiph-web