本文介绍了numpy.polyval()的反函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道np.polyval()是否有一个方便的逆函数,我在其中给出y值并求解x?

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?

推荐答案

这样的事情怎么样?

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.])

poly1d对象实现算术运算以返回新的poly1d对象,因此p - y是新的poly1d:

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])

poly1droots属性返回您期望的结果.

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

这篇关于numpy.polyval()的反函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 08:48