python: fsolve with unknown inside the upper limit

2019-04-16 08:08发布

Is it possible to apply fsolve method for an integral with the unknown in the upper limit and in the integrand??? I am ussing quad method for integration in python.

Thanks in advance!!!

1条回答
再贱就再见
2楼-- · 2019-04-16 09:00

Sure.

Suppose you want to find x such that the integral over t from t=0 to t=x of t*(1-x*t) is 0. You can do this by defining two functions. integrand(t, x) will evaluate t*(1-x*t), and func(x) will integrate integrand using quad, with x as both the upper limit of the integration, and as the extra argument of the integrand. Here's a demo:

import numpy as np
from scipy.integrate import quad
from scipy.optimize import fsolve


def integrand(t, x):
    return t*(1 - x*t)


def func(x):
    y, err = quad(integrand, 0, x, args=(x,))
    return y


# Use 1.0 as the initial guess.  Note that a bad initial guess
# might generate a warning and return the degenerate solution at x=0.
sol = fsolve(func, 1.0)

print "Solution:      ", sol[0]

# The exact solution that we want is sqrt(3/2)
print "Exact solution:", np.sqrt(1.5)

Output:

Solution:       1.22474487139
Exact solution: 1.22474487139
查看更多
登录 后发表回答