math.frexp

Chris Angelico rosuav at gmail.com
Fri Jul 15 07:48:10 EDT 2016


On Fri, Jul 15, 2016 at 9:39 PM, Steven D'Aprano <steve at 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



More information about the Python-list mailing list