I need help writing a method that receives a function, and some number y and returns x such that f(x) = y
. The function is differentiable using Newton's method:
from random import *
def diff_param(f,h=0.001):
return (lambda x: (f(x+h)-f(x))/h)
def NR(func, deriv, epsilon=10**(-8), n=100, x0=None):
""" returns a number such that f(number) == 0"""
if x0 is None:
x0 = uniform(-100.,100.)
x=x0; y=func(x)
for i in range(n):
if abs(y)<epsilon:
#print (x,y,"convergence in",i, "iterations")
return x
elif abs(deriv(x))<epsilon:
#print ("zero derivative, x0=",x0," i=",i, " xi=", x)
return None
else:
#print(x,y)
x = x- func(x)/deriv(x)
y = func(x)
#print("no convergence, x0=",x0," i=",i, " xi=", x)
return None
I need to write a method source(f,y)
that returns the x
such that f(x) = y
.
def source(f,y):
You need to find the zeros of g(x) = f(x)-y :
This returns a single
x
, but there may be others. To find them you need to try other initial valuesx0
.