Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #111469

Re: math.frexp

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: math.frexp
Date 2016-07-15 21:48 +1000
Message-ID <mailman.16.1468583297.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>

Show all headers | View raw


On Fri, Jul 15, 2016 at 9:39 PM, Steven D'Aprano <steve@pearwood.info> wrote:
> py> from math import frexp
> py> x = 2.5
> py> y = 3.5
> py> x*y
> 8.75
> py> m1, e1 = math.frexp(x)
> py> m2, e2 = math.frexp(y)
> py> m1*m2 * 2.0**(e1 + e2)
> 8.75
>
>
> Looks good to me. So let's try a less naive version of product():
>
>
> def product_scaled(values):
>     scale = 0
>     prod = 1.0
>     for a in values:
>         m1, e1 = math.frexp(a)
>         m2, e2 = math.frexp(prod)
>         scale += (e1 + e2)
>         prod *= (m1*m2)
>     return (prod * 2.0**scale)
>
>
> py> product_scaled([2.5, 3.5])  # expected 8.75
> 2.734375
>

You're chaining your product twice. (Also your scale, although that
appears to be correct.) Changing it to "prod = m1 * m2" gives 8.75.

But what do you gain by this? You're still stuffing the result back
into a float at the end, so all you do is change from getting
float("inf") to getting OverflowError. How can you make it not
overflow?

ChrisA

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


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