Python 使用 fsolve 找到解决方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15995913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:32:48  来源:igfitidea点击:

using fsolve to find the solution

pythonnumpyscipy

提问by dustin

import numpy as np
from scipy.optimize import fsolve

musun = 132712000000
T = 365.25 * 86400 * 2 / 3
e = 581.2392124070273


def f(x):
    return ((T * musun ** 2 / (2 * np.pi)) ** (1 / 3) * np.sqrt(1 - x ** 2)
        - np.sqrt(.5 * musun ** 2 / e * (1 - x ** 2)))


x = fsolve(f, 0.01)
f(x)

print x

What is wrong with this code? It seems to not work.

这段代码有什么问题?它似乎不起作用。

采纳答案by Simon

fsolve()returns the roots of f(x) = 0(see here).

fsolve()返回f(x) = 0(see here)的根。

When I plotted the values of f(x)for xin the range -1 to 1, I found that there are roots at x = -1and x = 1. However, if x > 1or x < -1, both of the sqrt()functions will be passed a negative argument, which causes the error invalid value encountered in sqrt.

当我在 -1 到 1 的范围内绘制f(x)for的值时x,我发现在x = -1和处有根x = 1。但是,如果x > 1x < -1,这两个sqrt()函数都将传递一个负参数,这会导致错误invalid value encountered in sqrt

It doesn't surprise me that fsolve()fails to find roots that are at the very ends of the valid range for the function.

fsolve()无法找到位于函数有效范围末端的根,这并不令我感到惊讶。

I find that it is always a good idea to plot the graph of a function before trying to find its roots, as that can indicate how likely (or in this case, unlikely) it is that the roots will be found by any root-finding algorithm.

我发现在试图找到它的根之前绘制一个函数的图形总是一个好主意,因为这可以表明任何寻根找到根的可能性(或在这种情况下,不太可能)算法。

回答by HYRY

Because sqrtreturns NaN for nagative argument, you function f(x) is not calculatable for all real x. I change your function to use numpy.emath.sqrt()which can output complex values when the argument < 0, and returns the absolute value of the expression.

因为sqrt为否定参数返回 NaN,所以函数 f(x) 无法计算所有实数 x。我将您的函数更改为使用numpy.emath.sqrt()它可以在参数 < 0 时输出复数值,并返回表达式的绝对值。

import numpy as np
from scipy.optimize import fsolve
sqrt = np.emath.sqrt

musun = 132712000000
T = 365.25 * 86400 * 2 / 3
e = 581.2392124070273


def f(x):
    return np.abs((T * musun ** 2 / (2 * np.pi)) ** (1 / 3) * sqrt(1 - x ** 2)
        - sqrt(.5 * musun ** 2 / e * (1 - x ** 2)))

x = fsolve(f, 0.01)
x, f(x)

Then you can get the right result:

然后你可以得到正确的结果:

(array([ 1.]), array([ 121341.22302275]))

the solution is very close to the true root, but f(x) is still very large, because f(x) has a very large factor: musun.

解非常接近真根,但 f(x) 仍然非常大,因为 f(x) 有一个非常大的因子:musun。