Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse function of numpy.polyval()

Tags:

python

numpy

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?

like image 817
Yuxiang Wang Avatar asked May 20 '14 01:05

Yuxiang Wang


1 Answers

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.

like image 139
Warren Weckesser Avatar answered Sep 21 '22 14:09

Warren Weckesser