0

Any help to compute this integration, F function is defined using the f function which involves the first integration, finally, integrate F.

from scipy.integrate import quad

f = lambda x,a : a**2*x

def F(s,a):
  return quad(f,0,s,args=(a,))
quad(F,0,5,args=(4,))

Got the error:

      2 def F(s,a):
      3   return quad(f,0,s,args=(a,))
----> 4 quad(F,0,5,args=(4,))
      5 
    446     if points is None:
    447         if infbounds == 0:
--> 448             return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
    449         else:
    450             return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)

TypeError: must be real number, not tuple
finefoot
  • 9,914
  • 7
  • 59
  • 102
mathfun
  • 101
  • 7

2 Answers2

1

Have a look at the return values of scipy.integrate.quad:

Returns:

y: float The integral of func from a to b.

abserr: float An estimate of the absolute error in the result.

...

So there are multiple return values (a tuple) and that's why you're getting the TypeError: must be real number, not tuple message.

I guess, you're just interested in the integral value quad(...)[0] so that's what your F should return:

from scipy.integrate import quad

f = lambda x, a: a**2 * x
F = lambda x, a: quad(f, 0, x, args=(a,))[0]

I = quad(F, 0, 5, args=(4,))
print(I)

Which prints:

(333.33333333333337, 3.700743415417189e-12)
finefoot
  • 9,914
  • 7
  • 59
  • 102
  • One more question, can you help? from scipy.integrate import quad from math import sqrt f = lambda x, a: a**2 * x F = lambda x, a: quad(f, 0, x, args=(a,))[0] rho = 5 I = quad(sqrt(F(??)-F(rho,a)), 0, rho, args=(4,)) print(I) – mathfun Jul 25 '19 at 18:15
0

Another way of looking at the problem is to realize that you're integrating the function a**2 * y over the triangle spanned by the points [0, 0], [5, 0], and [5, 5]. You could then use triangle quadrature from quadpy (one of my projects) to compute the value:

import quadpy

a = 4.0


def g(x):
    return a ** 2 * x[1]


scheme = quadpy.triangle.dunavant_05()
val = scheme.integrate(g, [[0.0, 0.0], [5.0, 0.0], [5.0, 5.0]])
print(val)

This should require a much fewer function evaluations that the nested quad approach.

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249