faqts : Computers : Programming : Languages : Python : Snippets : Maths

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 4 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes

Entry

Approximating x in function

Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 120, Frank Niessink


"""
Packages: maths.financial
"""
"""
Hi,
Here's a module (actually it contains only one function) for the
snipper repository. The function approximates the x value that
results in a certain y value for a function. I use it for a program
that calculates the internal rate of return (IRR) for a portfolio, e.g.
suppose my portfolio is worth $Y, my cashflows are [c1,c2,c3], then
what is the IRR that results in that value Y.
"""
def solve(func,y,minx,maxx,precision=0.000001):
	""" 
	solve finds an estimate between minx and maxx such that:
	y_estimate ~= func(x_estimate), with abs(y - y_estimate) <= precision
	func should be monotonic increasing or decreasing between minx and maxx
	and take one float as argument.
	Some examples:
	inverse of 2:
	>>> solve(lambda x: 1.0/x, 2, 0.1, 1)
	0.500000190735
	>>>
	inverse of 3:
	>>> solve(lambda x: 1.0/x, 3, 0.1, 1)
	0.333333301544
	>>>
	square root of 2:
	>>> solve(lambda x: x*x, 2, 1, 2)
	1.41421365738
	>>>
	square root of 2, but negative:
	>>> solve(lambda x: x*x, 2, -2, -1)
	-1.41421365738
	>>>
	"""
	# if func is decreasing: reorder parameters to construct equivalent
	# increasing function
	if func(minx) > func(maxx):
		y = func(minx) - y
		func = lambda x,f=func,m=minx: f(m) - f(x)
	x_estimate = minx+(maxx-minx)/2.0		# start halfway
	y_estimate = func(x_estimate)			# initial estimate
	while abs(y - y_estimate) > precision:
		if y_estimate > y:
			maxx = x_estimate
		else:
			minx = x_estimate
		x_estimate = minx+(maxx-minx)/2.0
		y_estimate = func(x_estimate)
	return x_estimate
def _test():
    print solve(lambda x: 1.0/x, 3, 0.1, 1)
if __name__ == "__main__":
    _test()