【问题标题】:How can I isolate the result of scipy.integrate.quad function, rather than having the result and the error of the calculation?如何隔离 scipy.integrate.quad 函数的结果,而不是计算结果和错误?
【发布时间】:2013-07-23 01:18:12
【问题描述】:

我正在尝试创建一个整数值数组,以便在计算中进一步使用。问题是integrate.quad 返回(答案,错误)。我不能在其他计算中使用它,因为它不是浮点数;它是一组两个数字。

【问题讨论】:

    标签: python arrays scipy integration quad


    【解决方案1】:

    @BrendanWood 的回答很好,你已经接受了,所以它显然对你有用,但是还有另一个 python 习惯用法来处理这个问题。 Python 支持“多重赋值”,也就是说你可以说x, y = 100, 200 来赋值x = 100y = 200。 (有关 Python 入门教程中的示例,请参阅 http://docs.python.org/2/tutorial/introduction.html#first-steps-towards-programming。)

    要将此想法与quad 一起使用,您可以执行以下操作(对 Brendan 示例的修改):

    # Do the integration on f over the interval [0, 10]
    value, error = integrate.quad(f, 0, 10)
    
    # Print out the integral result, not the error
    print('The result of the integration is %lf' % value)
    

    我发现这段代码更容易阅读。

    【讨论】:

    • +1,我真的更喜欢将结果显式分配给有意义的名称,否则之后太容易混淆
    【解决方案2】:

    integrate.quad 返回两个值的tuple(在某些情况下可能还有更多数据)。您可以通过引用返回的元组的第零个元素来访问答案值。例如:

    # import scipy.integrate
    from scipy import integrate
    
    # define the function we wish to integrate
    f = lambda x: x**2
    
    # do the integration on f over the interval [0, 10]
    results = integrate.quad(f, 0, 10)
    
    # print out the integral result, not the error
    print 'the result of the integration is %lf' % results[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      相关资源
      最近更新 更多