【问题标题】:How to find roots for a numpy array如何找到一个numpy数组的根
【发布时间】:2018-07-24 20:36:39
【问题描述】:

我想知道如何找到数组的脚。我现在拥有的是:

import numpy as np
from scipy.optimize import brentq as find_root

t = np.linspace(0, 100)

def f(x):
    return x ** 2 - t

a = find_root(f, -400, 400)

print(a)

它给了我一个类型数组说:

TypeError: only size-1 arrays can be converted to Python scalars. 

我知道原因是 find_root 只能在其参数中采用标量。我想要的是使“a”成为一个凹凸不平的数组,在给定每个可能的 t 值的情况下找到函数的根。这是否意味着我需要为 find_root 编写一个循环?或者我需要在定义函数之前编写一个循环吗?最简单的方法是什么? 非常感谢您的帮助。

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    是的,在这种情况下,只循环参数可能是最简单的。

    import numpy as np
    from scipy.optimize import brentq as find_root
    
    def f(x, t):
        return x ** 2 - t
    
    a = [find_root(f, 0, 400,args=(i,)) for i in np.linspace(1,10,10)]
    
    print(a)
    

    请注意,我向您的函数 f 引入了一个参数 t,您可以使用 find_rootargs 参数将值传递给它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-28
      • 2021-05-23
      相关资源
      最近更新 更多