【问题标题】:Why can't I run linspace() through my python generator? (Beginner)为什么我不能通过我的 python 生成器运行 linspace()? (初学者)
【发布时间】:2021-03-08 05:43:40
【问题描述】:

我的函数使用一种方法来计算三次方程的系数,然后运行 ​​for 循环并生成。然后,我在函数外部使用另一个 for 循环对其进行迭代,以调用它并列出三次方程的根。

我可以在输入标量值时运行它,但是当我将其中一个变量作为带有np.linspace() 的序列时,它会输出The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

这是我的代码:

Tlnh = np.linspace(18,100,10)
Tch = 33.145 #K
Pch = 1.2964 #MPa
Dch = 31.263 #kg/m3
wh = -0.219 
 
def root((T,P,Tc,Pc,w, R=8.314):
      .
      .
      .

      #Using np.roots() and only printing out the real positive number
      coeff = [1,p1, p2, p3]
      roots = np.roots(coeff)

      #prints out the real positive roots only. 
      for i in range(len(roots)):
          if np.isreal(roots[i]):
          return np.real(roots[i]) 

      return 

g = [h for h in root(Tlnh,p1h,Tch,Pch,wh)]

输出:

ValueError                                Traceback (most recent call last)
<ipython-input-78-4b4a96b379ea> in <module>
      1 #Hydrogen Densities for Pr = 0.8
      2 #r =[h for h in root(Tlnh,p1h,Tch,Pch)]
----> 3 g = [h for h in root(Tlnh,p1h,Tch,Pch,wh)]
      4 print(g)

<ipython-input-76-20726dad64bd> in root(T, P, Tc, Pc, w, R)
     44     #Using np.roots() and only printing out the real positive number
     45     coeff = [1,p1, p2, p3]
---> 46     roots = np.roots(coeff)
     47 
     48     #prints out the real positive roots only.

<__array_function__ internals> in roots(*args, **kwargs)

D:\anaconda3\lib\site-packages\numpy\lib\polynomial.py in roots(p)
    220 
    221     # find non-zero array entries
--> 222     non_zero = NX.nonzero(NX.ravel(p))[0]
    223 
    224     # Return an empty array if polynomial is all zeros

<__array_function__ internals> in nonzero(*args, **kwargs)

D:\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in nonzero(a)
   1906 
   1907     """
-> 1908     return _wrapfunc(a, 'nonzero')
   1909 
   1910 

D:\anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
     56 
     57     try:
---> 58         return bound(*args, **kwds)
     59     except TypeError:
     60         # A TypeError occurs if the object does have such a method in its

    ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(

)

【问题讨论】:

    标签: python numpy jupyter-notebook


    【解决方案1】:

    编辑:np.roots 是有问题的调用 - 因为它需要一维系数数组。每个系数必须是一个数字,而不是一个数组。

    原答案供参考:

    问题很可能出在这条线上:

    if np.isreal(...):
    

    (理论上,您应该已经获得了精确定位线路的回溯)。

    但是为什么呢?好吧,该函数为您提供如下内容:

    if [True, False, False, True, ....]:
    

    现在if 运算符应该如何解释这个结果?是真的吗 还是假的?答:它放弃并抛出你观察到的错误。

    【讨论】:

    • 该错误确实包含回溯,但对于许多初学者来说,这与我们或他们自己无关。
    • 我能否将函数内的所有内容封装在一个 for 循环中,以便它从 linspace() 函数中逐一运行和计算?
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2022-06-14
    • 2015-06-12
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多