【问题标题】:Python - How to plot argument in integral that is not the value being integratedPython - 如何在不是积分值的积分中绘制参数
【发布时间】:2018-10-15 07:46:50
【问题描述】:

我想将没有封闭形式解决方案的函数与未知变量集成,然后绘制与未知变量的关系图。为了尝试更简单的测试,我尝试使用f(x,c) = (x^2+c) 的积分,相对于x 积分并使用c 的不同值进行绘图。但是,下面的代码得到了错误

只有 size-1 的数组可以转换为 Python 标量

即使一个数字的积分,例如integral(5),似乎返回了正确的标量值。

import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate


def f(x,c):
    return x**2+c

def integral(c):
    return integrate.quad(f,0,10, args = (c,))[0]
y = np.linspace(0,20,200)


plt.plot(y, integral(y))

【问题讨论】:

  • 你真的不应该写一个叫做int的函数。它与the built-in function 造成不必要的混淆。
  • 你的变量test是什么?
  • 我猜test应该是f,因为它是上面定义的函数
  • 已编辑将 int 函数更改为整数并修复了测试错字

标签: python plot scipy integral


【解决方案1】:

您传递一个 numpy 数组作为参数 c,而您想在 x 上集成 c 的所有项目。因此你可以使用这个:

def f(x,c):
    return x**2+c

def integrate_f(c):
    result = np.zeros(len(c))
    counter = 0
    for item in c:
        result[counter] = integrate.quad(f,0,10, args = (item))[0]
        counter +=1
    return result

c_array = np.linspace(0,1,200)
plt.plot(c_array, integrate_f(c_array))

【讨论】:

    【解决方案2】:

    onno 有点快。但这是我的类似解决方案。你需要遍历所有不同的c

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy import integrate
    
    
    def f(x,c):
        return x**2+c
    
    def getIntegral(c_list):
        result = []
        for c in c_list:
            integral = integrate.quad(f,0,10,args = c)[0]
            result.append(integral)
        return result
    
    if __name__ == "__main__":
    
    
        c_list = np.linspace(0,20,200)
    
        plt.plot(c_list, getIntegral(c_list))
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 2022-10-05
      • 1970-01-01
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2017-02-02
      • 2016-08-20
      • 2021-02-21
      相关资源
      最近更新 更多