How can I isolate the result of scipy.integrate.quad function, rather than having the result and the error of the calculation?

StackOverflow https://stackoverflow.com/questions/17819193

質問

I'm trying to create an array of integral values that will be used further in calculations. The problem is that integrate.quad returns (answer, error). I can't use that in other calculations because it isn't a float; it is a set of two numbers.

役に立ちましたか?

解決 2

integrate.quad returns a tuple of two values (and possibly more data in some circumstances). You can access the answer value by referring to the zeroth element of the tuple that is returned. For example:

# 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]

他のヒント

@BrendanWood's answer is fine, and you've accepted, so it obviously works for you, but there is another python idiom for handling this. Python supports "multiple assignment", meaning you can say x, y = 100, 200 to assign x = 100 and y = 200. (See http://docs.python.org/2/tutorial/introduction.html#first-steps-towards-programming for an example in the introductory python tutorial.)

To use this idea with quad, you can do the following (a modification of Brendan's example):

# 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)

I find this code easier to read.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top