I'am using a small program calculating by dichotomy the root of a function (i.e. find x
when f(x)=0
). (I admit I stole this program from some SO
post, but I can't give the reference nor thank the author because I don't remember where it was...)
The output I have is:
Root is: -0.567143
Delta with 0 is: 0.000000000166
I would like to also output the expression of the function I am working on, just as written in def f(x)
so as to have:
Function is: x + np.exp(x)
Root is: -0.567143
Delta with 0 is: 0.000000000166
I wonder how to do that...? Can def f(x)
be modified to store the function writing somewhere? Or is it necessary to do another type of manipulation elsewhere?
My program is:
def samesign(a, b):
return a * b > 0
def dichotomy(func, low, high, tolerance=None):
# func(low) and func(high) must have opposite signs
assert not samesign(func(low), func(high)), ("\n"
"Assertion failed!\n"
"Replace low or high")
condition = True
while condition:
midpoint = (low + high) / 2.0
if samesign(func(low), func(midpoint)):
low = midpoint
else:
high = midpoint
if tolerance is not None and abs(high - low) < tolerance:
break
condition = abs(high - low) > tolerance
return midpoint
def f(x):
# Define function
return x + np.exp(x)
x = dichotomy(f, -1, 0, 1E-9)
import inspect
line_return = inspect.getsourcelines(f)[0][-1]
llr = len(line_return)
name = line_return[11 : llr-1]
print(f'Function is: {name}')
print(f'Root is: {x: .6f}')
print(f'Delta with 0 is: {f(x): .12f}')