用python找到超越方程的根 [英] Find root of a transcendental equation with python

查看:82
本文介绍了用python找到超越方程的根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须解决以下超越方程

I have to solve the following transcendental equation

cos(x)/x=c

对于给定的常数 c.

例如我在 Mathematica 中做了一个简短的代码,在那里我为常数 c 生成了一个随机值列表

For example I did a short code in Mathematica, where I generated a list of random values for constant c

const = Table[RandomReal[{0, 5}], {i, 1, 10}]

(*{1.67826, 0.616656, 0.290878, 1.10592, 0.0645222, 0.333932, 3.59584, \
2.70337, 3.91535, 2.78268}*)

比我定义的函数

f[x_, i_] := Cos[x]/x - const[[i]]

并开始寻找根源:

Table[FindRoot[f[x, i] == 0, {x, 0.1}][[1, 2]], {i, 1, Length[const]}]
(*{0.517757, 0.947103, 1.21086, 0.694679, 1.47545, 1.16956, 0.26816, \
0.347764, 0.247615, 0.338922}*)

<小时>

现在我很想在 python 中编写类似的东西(可能使用 numpy?),但我真的找不到像这样的问题的任何好的现有答案.有人可以帮忙吗?


Now I would love to programme something similar in python (probably using numpy?) but I can't really find any good existing answer to a problem like that. Could somebody help?

推荐答案

我过去实现的一种方法是使用 scipy.optimize.minimize 来找到平方函数的最小值.

One way that I have achieved this in the past is to use scipy.optimize.minimize to find the minima of the squared function.

from scipy.optimize import minimize
from numpy import cos

def opt_fun(x, c):
    return (cos(x)/x - c)**2

const = 1.2
res = minimize(lambda x: opt_fun(x, const), x0=0.001)

# Check if the optimization was successful
print(res.success)
# >> True

# Extract the root from the minimization result
print(res.x[0])
# >> 0.65889256782472172

这绝不是万无一失,但它可以快速而准确.例如,如果有多个根,minimize 将在您选择的初始点的下坡方向"中找到一个,这就是为什么我在上面选择了一个小的正值.

This is by no means fool-proof, but it can be quick and accurate. If there are multiple roots, for instance, minimize will find the one in the 'downhill direction' from the initial point you select which is why I've chosen a small positive value above.

另一个需要注意的问题是具有显着不同数量级的数字,这对于最小化问题总是正确的.在你的等式中,随着 c 变得非常大,第一个正根变得非常小.如果您最终试图在这种情况下找到根源,您可能需要将 x 都缩放到接近 1 以获得准确的结果(此处举个例子).

One other issue to keep an eye out for, which is always true with minimization problems, is numbers with dramatically different orders of magnitude. In your equation, as c gets very large, the first positive root gets very small. If you wind up trying to find roots in that circumstance, you may need to scale both x to be near to 1 in order to get accurate results (an example here).

这篇关于用python找到超越方程的根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆