Let's say I want to integrate x**2
from 0 to 1. I do it using the scipy.integrate.quad
:
from scipy import integrate
def f(x): return x**2
I = integrate.quad(f, 0, 1)[0]
print(I)
Questions: Is there any way to know how many times the user-defined function f
gets called by the quad
? I want to do it as I am interested to know how many have been utilized by quad
to evaluate the integral.
Sure. Use a call-counting wrapper:
import functools
def counted_calls(f):
@functools.wraps(f)
def count_wrapper(*args, **kwargs):
count_wrapper.count += 1
return f(*args, **kwargs)
count_wrapper.count = 0
return count_wrapper
And pass the wrapped version to quad
:
wrapped = counted_calls(f)
integrate.quad(wrapped, 0, 1)
print(wrapped.count)
Demo, with a call count of 21.
I've specifically avoided using a global counter or using counted_calls
as a decorator on the f
definition (though you can use it as a decorator if you want), to make it easier to take separate counts. With a global, or using it as a decorator, you'd have to remember to manually reset the counter every time.
Just add to a global whenever f
is called:
from scipy import integrate
count = 0
def f(x):
global count
count += 1
return x ** 2
I = integrate.quad(f, 0, 1)[0]
print(I)
print('called', count, 'times')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With