ValueError:具有多个元素的数组的真值不明确,请在使用Numpy和Scipy时使用.any()或.all()

fcy6dtqo  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(110)

我正在用numpy和scipy在Python中计算一个积分。
这是我目前的代码:

import scipy
import numpy as N

d = 160
w = 1.8
np = 265

def f(x):
    return N.sin(N.power(x, 2))

inta = scipy.integrate.quad(f, 0, N.sqrt(N.divide(N.pi, 2)))
a = N.power((N.divide(N.multiply(N.multiply(2, N.sqrt(2)), inta), d)), 2)
s = N.sqrt(N.divide(N.pi, a))

def funx(u):
    return N.cos(N.multiply(N.divide(a, 2), N.square(u)))

x = scipy.integrate.quad(funx, 0, N.multiply(N.divide(1, np), s))
print(x)

但是,在计算最后一个积分时出现错误

x = scipy.integrate.quad(funx, 0, N.multiply(N.divide(1, np), s))

“值错误:有多个元素的数组的真值是不明确的。使用a.any()或a.all()"。我特别困惑为什么第一个积分运行良好,但第二个给出了错误。
如何修复此错误?
编辑:
完整的错误消息:

Traceback (most recent call last):
  File "C:\Users\eeerm\PycharmProjects\GDSGenerator\GDSWriter\stackOverflowq.py", line 20, in <module>
    x = scipy.integrate.quad(funx, 0, N.multiply(N.divide(1, np), s))
  File "C:\Users\eeerm\PycharmProjects\GDSGenerator\venv\lib\site-packages\scipy\integrate\_quadpack_py.py", line 408, in quad
    flip, a, b = b < a, min(a, b), max(a, b)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
fivyi3re

fivyi3re1#

默认情况下,quad返回一个元组,如下所示:(value_of_integration, estimated_error) .
所以,

inta, inta_error = integrate.quad(f, 0, N.sqrt(N.divide(N.pi, 2)))

还有

x, x_error = integrate.quad(funx, 0, N.multiply(N.divide(1, np), s))

也许你需要键入这个,在所有:

import scipy.integrate as integrate

相关问题