Develop and Create a program to take in a function and then find a root of that function
import matplotlib.pyplot as plt
import numpy as np
%config InlineBackend.figure_format='retina'
def f(x):
return x*(x**2-5)
f(2)
X=np.arange(-3,3,0.1)
plt.plot(X,f(X))
plt.grid()
def Df(x):
h=0.00000000001
return (f(x+h)-f(x))/h
Df(2)
plt.plot(X,f(X))
plt.plot(X,Df(X),c='r')
plt.grid()
x0=2
xold=x0
for c in range(0,20):
xnew = xold - f(xold)/Df(xold)
xold=xnew
print(xnew)
5**0.5
x0=10000
xold=x0
xchecker=x0+1
xnew=x0-1
while ((xchecker-xnew)**2>0.0000000001) and ((xnew-xold)**2<10000):
xchecker=xold
xnew = xold - f(xold)/Df(xold)
xold=xnew
print(xnew)
def Newton(x0):
xold=x0
xchecker=x0+1
xnew=x0-1
count=1
while ((xchecker-xnew)**2>0.0000000001) and (count<=1000):
count+=1
xchecker=xold
xnew = xold - f(xold)/Df(xold)
xold=xnew
return xnew
Newton(-1)
plt.plot(X,f(X))
for c in range(-10,10):
print(Newton(c))
import sympy as sym
x = sym.symbols('x')
x
f = x*(x**2-5)
f
Df = sym.diff(f,x)
Df
f = sym.lambdify(x,f)
Df = sym.lambdify(x,Df)
X = np.arange(-2,1,0.01)
plt.plot(X,f(X))
plt.plot(X,Df(X))
from scipy.optimize import newton
def g(x):
return x*(x**2-5)
newton(g,2)
sym.roots(f,x)
g(x)