numpy / numpy/numpy

BUG? DOC? Why is exp(p*log(x)) faster than power(x, p)?

Open
#22,651 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

00 - Bug 33 - Question
Dominant language
Python
Stars
32.8k
Forks
12.8k
Avg merge
1d 7h
Merged PRs (30d)
197

Description

Describe the issue:

I assume this is a documentation issue rather than a real bug.

power() is very slow.
I suppose it must be slow in order to achieve accuracy?
Maybe the documentation can explain how much accuracy is lost by using the faster approach exp(p*log(x)), so that users can decide between the two approaches.

Reproduce the code example:
import numpy as np

def power(x: np.ndarray, p: float):
    temp = np.empty_like(x)
    np.log(x, out=temp)
    np.multiply(p, temp, out=temp)
    np.exp(temp, out=temp)
    return temp

x = np.logspace(-4, 4, 50_000_000)

%%timeit
power(x, 2.1)
"477 ms ± 34.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"

%%timeit
np.power(x, 2.1)
"2.71 s ± 32.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)"

np.allclose(power(x, 2.1), np.power(x, 2.1))
"True"
Error message:

No response

NumPy/Python version information:

1.22.4 3.9.7 (default, Sep 16 2021, 13:09:58)
[GCC 7.5.0]

Context for the issue:

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproduction code comparing the custom exp(log()) approach with np.power(x, 2.1), then investigate the accuracy difference across the shown input range. Done means documenting why np.power is slower and quantifying the accuracy tradeoff so users can choose between the approaches.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
performance
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.