Last active
December 10, 2016 16:31
-
-
Save shlaikov/a55e87eea2bf57b07efed528f14dfbb7 to your computer and use it in GitHub Desktop.
Newtone's method with using "matplotlib" (example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from matplotlib import mlab | |
import matplotlib.pyplot as plt | |
def f(x): | |
return 6*x**5-5*x**4-4*x**3+3*x**2 | |
def df(x): | |
return 30*x**4-20*x**3-12*x**2+6*x | |
def dx(f, x): | |
return abs(0 - f(x)) | |
def tangent(x): | |
return -0.0625 - 1.625 * x | |
def newtons_method(f, df, x0, e): | |
delta = dx(f, x0) | |
while delta > e: | |
x0 = x0 - f(x0)/df(x0) | |
delta = dx(f, x0) | |
print('root: ', x0) | |
print('f(x) = ', f(x0)) | |
def plot(point): | |
xmin = -1.0 | |
xmax = 1.5 | |
dx = 0.01 | |
xlist = mlab.frange(xmin, xmax, dx) | |
ylist1 = [f(x) for x in xlist] | |
ylist2 = [tangent(x) for x in xlist] | |
plt.figure("Newtone's method") | |
plt.plot(xlist, ylist1) | |
scatter1 = plt.scatter(0.0, 0.0) | |
scatter2 = plt.scatter(point, 0.0) | |
plt.errorbar(point, 0, xerr=0.08, yerr=1) | |
plt.plot(xlist, ylist2) | |
plt.tight_layout() | |
plt.grid() | |
plt.show() | |
def main(): | |
x0s = float(input('>> ')) | |
newtons_method(f, df, x0s, 1e-5) | |
plot(x0s) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment