numpy.poly1d ,求根优化,在 x 轴上移动多项式

发布于 2024-11-25 19:54:49 字数 427 浏览 5 评论 0原文

构建 n 阶多项式通常是一项简单的任务 并用 numpy 求根:

import numpy
f = numpy.poly1d([1,2,3])
print numpy.roots(f)
array([-1.+1.41421356j, -1.-1.41421356j])

但是,假设您想要一个类型的多项式:

f(x) = a*(x-x0)**0 + b(x-x0)**1 + ... + n(x-x0)**n

是否有一种简单的方法来构造 numpy.poly1d 类型函数 并找到根源?我尝试过 scipy.fsolve 但它非常不稳定,因为它很大程度上取决于起始值的选择 就我的具体情况而言。

提前致谢 此致 rrrak

编辑:将“多边形”(错误)更改为“多项式”(正确)

it is commonly an easy task to build an n-th order polynomial
and find the roots with numpy:

import numpy
f = numpy.poly1d([1,2,3])
print numpy.roots(f)
array([-1.+1.41421356j, -1.-1.41421356j])

However, suppose you want a polynomial of type:

f(x) = a*(x-x0)**0 + b(x-x0)**1 + ... + n(x-x0)**n

Is there a simple way to construct a numpy.poly1d type function
and find the roots ? I've tried scipy.fsolve but it is very unstable as it depends highly on the choice of the starting values
in my particular case.

Thanks in advance
Best Regards
rrrak

EDIT: Changed "polygon"(wrong) to "polynomial"(correct)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赠我空喜 2024-12-02 19:54:49

首先,你的意思肯定是多项式,而不是多边形?

在提供答案方面,您是否在所有术语中使用相同的“x0”值?如果是这样,则设 y = x - x0,求解 y 并使用 x = y + x0 得到 x。

如果需要,您甚至可以将其包装在 lambda 函数中。假设您想要表示

f(x) = 1 + 3(x-1) + (x-1)**2

那么,

>>> g = numpy.poly1d([1,3,1])
>>> f = lambda x:g(x-1)
>>> f(0.0)
-1.0

f 的根由下式给出:

f.roots = numpy.roots(g) + 1

First of all, surely you mean polynomial, not polygon?

In terms of providing an answer, are you using the same value of "x0" in all the terms? If so, let y = x - x0, solve for y and get x using x = y + x0.

You could even wrap it in a lambda function if you want. Say, you want to represent

f(x) = 1 + 3(x-1) + (x-1)**2

Then,

>>> g = numpy.poly1d([1,3,1])
>>> f = lambda x:g(x-1)
>>> f(0.0)
-1.0

The roots of f are given by:

f.roots = numpy.roots(g) + 1
追星践月 2024-12-02 19:54:49

如果 x0 的幂不同,例如:

f(x) = 3*(x-0)**0 + 2*(x-2)**1 + 3*(x-1)**2 + 2*(x-2)**3

可以使用多项式运算来计算最终展开的多项式:

import numpy as np
import operator

ks = [3,2,3,2]
offsets = [0,2,1,2]

p = reduce(operator.add, [np.poly1d([1, -x0])**i * c for i, (c, x0) in enumerate(zip(ks, offsets))])

print p

结果为:

   3     2
2 x - 9 x + 20 x - 14

In case x0 are different by power, such as:

f(x) = 3*(x-0)**0 + 2*(x-2)**1 + 3*(x-1)**2 + 2*(x-2)**3

You can use polynomial operation to calculate the finally expanded polynomial:

import numpy as np
import operator

ks = [3,2,3,2]
offsets = [0,2,1,2]

p = reduce(operator.add, [np.poly1d([1, -x0])**i * c for i, (c, x0) in enumerate(zip(ks, offsets))])

print p

The result is:

   3     2
2 x - 9 x + 20 x - 14
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文