7

I was wondering is there a convenient inverse function of np.polyval(), where I give the y value and it solves for x?

I know one way I could do this is:

import numpy as np

# Set up the question
p = np.array([1, 1, -10])
y = 100

# Solve
p_temp = p
p_temp[-1] -= y
x = np.roots(p_temp)

However my guess is most would agree on that this code has low readability. Any suggestions?

Yuxiang Wang
  • 8,095
  • 13
  • 64
  • 95

1 Answers1

14

How about something like this?

In [19]: p = np.poly1d([1, 1, -10])  # Use a poly1d to represent the polynomial.

In [20]: y = 100

In [21]: (p - y).roots
Out[21]: array([-11.,  10.])

The poly1d object implements the arithmetic operations to return a new poly1d object, so p - y is a new poly1d:

In [22]: p - y
Out[22]: poly1d([   1,    1, -110])

The roots attribute of a poly1d returns what you would expect.

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214