英文:
Extracting the converged? bool of scipy.optimize.newton() result
问题
Sure, here is the translated code part:
我正在尝试使用scipy.optimize.newton()找到函数的根。我使用的函数非常复杂,因此我决定进行一定次数的迭代,并在精度不被满足时保留最终答案。因此,我想知道何时发生了收敛,何时没有,在一个布尔变量中表示。
我遇到的问题是newton()返回一个二维数组,其中根的结果是第一个值,第二个值是一个具有多个值的对象,我似乎无法提取出收敛的值。
我尝试只查看newton返回函数的第二个值。这是我的代码:
from scipy.optimize import newton
def function(x):
return x**2-1
def fprime(x):
return 2*x
x0=5
test = newton(function, x0, fprime=None, args=(), tol=1.48e-08, maxiter=5, fprime2=None, x1=None, rtol=0.0, full_output=True, disp=False)
print(test[1])
这将产生以下输出:
converged: False
flag: 'convergence error'
function_calls: 7
iterations: 5
root: 1.0103336911991998
你想要的是一个仅包含'False'的变量(对于这个示例)。
英文:
I'm trying to find the <strike>minimum</strike> root of a function using scipy.optimize.newton(). The function I'm using is very complicated, and as a result I decided to have a set number of iterations and to keep the final answer even if the precision asked is not respected. As such, I would like to know when convergence happened and when it didn't, in one single bool variable.
The problem I'm running in is that newton() returns a 2 dimensional array with the root result as the first value, and the second value is an object with several values, of which I can't seem to extract the converged one.
I tried to look only at the second value of the newton return function. This is my code:
from scipy.optimize import newton
def function(x):
return x**2-1
def fprime(x):
return 2*x
x0=5
test = newton(function, x0, fprime=None, args=(), tol=1.48e-08, maxiter=5, fprime2=None, x1=None, rtol=0.0, full_output=True, disp=False)
print(test[1])
Which gives
converged: False
flag: 'convergence error'
function_calls: 7
iterations: 5
root: 1.0103336911991998
and what I would like is just one variable with 'False' in it (for this example)
答案1
得分: 0
在调用 scipy.optimize.newton
时,newton
返回一个包含两个元素的元组,第一个元素是根,第二个元素是一个 RootResults
对象。如果你想获取 RootResults
对象的 converged
属性,只需使用点表示法,即 some_obj.attribute
。
root, r = newton(function, x0, fprime=None, args=(), tol=1.48e-08, maxiter=5, fprime2=None, x1=None, rtol=0.0, full_output=True, disp=False)
converged_flag = r.converged
print(converged_flag)
英文:
In your way of calling scipy.optimize.newton
, newton
returns a 2-element tuple, and the first element is the root, the second is a RootResults
object. If you want to get the converged
attribute of the RootResults
object, you just need to
use dot notation, some_obj.attribute
.
root, r = newton(function, x0, fprime=None, args=(), tol=1.48e-08, maxiter=5, fprime2=None, x1=None, rtol=0.0, full_output=True, disp=False)
converged_flag = r.converged
print(converged_flag)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论