示例#1
0
文件: nroot.py 项目: EliMor/MathToys
	def __apply_newton(self,guess,i):
		#not going to scale well. 
		ans = newton.solve(guess, self.max_iter, self.tol, i, self.f)
		if np.isnan(ans):
			c = 0
			rev = np.log(self.number)
			#traverse log as new guess
			while  np.isnan(rev)==False and np.isnan(ans) and c < 10:
				ans = newton.solve(int(rev), self.max_iter, self.tol, i, self.f)
				c += 1
				rev = np.log(rev)

		return ans
示例#2
0
def test1(debug_solve=True):
    """
    Test Newton iteration for the square root with different initial
    conditions.
    """
          
    # points to evaluate polynomial
    x = np.linspace(-5., 5, 1000)                           
    g1 = x*np.cos(np.pi*x)
    g2 = 1-.6*x**2

    plt.figure(1)       # open plot figure window
    plt.clf()           # clear figure
    ax = plt.subplot(111)
    ax.plot(x, g1, 'b-', label='g1')  # connect points with a blue line
    ax.plot(x, g2, 'r-', label='g2')
    ax.legend(loc='lower center')

    for x0 in [-2., -1.5, -1., 1.5]:
        print " "  # blank line
        x, iters = solve(fvals_sqrt, x0, debug=debug_solve)
        print "Initial guess: x = %22.15e" % x0
        print "solve returns x = %22.15e after %i iterations " % (x,iters)
        fx = 1-.6*x**2
        print "the value of f(x) is %22.15e" % fx
        # Add data points  (polynomial should go through these points!)
        ax.plot(x, fx, 'ko')   # plot as red circles

    plt.title("Intersections")

    plt.savefig('intersections.png')   # save figure as .png file
示例#3
0
def test1(debug_solve=False):
    """
    Find 4 intersections.
    """
    xs = []
    ys = []
    for x0 in [-2.5, -1.7, -1., 1.3]:
        print " "  # blank line
        x,iters = solve(fvals, x0, debug=debug_solve)
        print "solve returns x = %22.15e after %i iterations " % (x,iters)
        fx,fpx = fvals(x)
        print "the value of f(x) is %22.15e" % fx
        xs.append(x)
        ys.append(gvals_g1(x)[0])
        #assert abs(x-2.) < 1e-14, "*** Unexpected result: x = %22.15e"  % x
    x = np.linspace(-5, 5, 1001)
    y1, y1p = gvals_g1(x)
    y2, y2p = gvals_g2(x)
    plt.figure(1)       # open plot figure window
    plt.clf()           # clear figure
    plt.plot(x,y1,'b-')  # connect points with a blue line
    plt.plot(x,y2,'r-')  # connect points with a blue line
    plt.legend(["g1", "g2"])

    # Add data points  (polynomial should go through these points!)
    plt.plot(xs,ys,'ko')   # plot as red circles
    #plt.ylim(-2,8)         # set limits in y for plot

    plt.title("functions and thier intersections")

    plt.savefig('hw3.png')   # save figure as .png file
示例#4
0
def intersect(g1vals,g2vals,x0):
    '''
    given two functions and initial guess this function returns their intersections
    '''
      
    x, iterations = solve(  lambda x: ( g1vals(x)[0] - g2vals(x)[0], g1vals(x)[1] - g2vals(x)[1] ) , x0)
    
    return x
示例#5
0
def test1(debug_solve=False):
	"""
	Test Newton iteration for the square root with different initial
	conditions.
	"""
	is_values = []
	for x0 in [-2.5,-1.5,-0.5,1.5]:
		print " "
		x, iters = solve(g_fcns, x0, debug_solve)
		print "solve returns x = %22.15e after %d iterations " % (x,iters)
		fx,fpx = g_fcns(x)
		print "the value of f(x) is %22.15e" % fx
		is_values.append(x)
		#assert abs(x-2.) < 1e-14, "*** Unexpected result: x = %22.15e" % x
	plot_fcns(asarray(is_values))
示例#6
0
def test1(debug_solve=False):
    """
	Test Newton iteration for the square root with different initial
	conditions.
	"""
    is_values = []
    for x0 in [-2.5, -1.5, -0.5, 1.5]:
        print " "
        x, iters = solve(g_fcns, x0, debug_solve)
        print "solve returns x = %22.15e after %d iterations " % (x, iters)
        fx, fpx = g_fcns(x)
        print "the value of f(x) is %22.15e" % fx
        is_values.append(x)
        #assert abs(x-2.) < 1e-14, "*** Unexpected result: x = %22.15e" % x
    plot_fcns(asarray(is_values))
def plot_intersections(fvals_func):
    x = np.linspace(-5, 5, 300)
    
    xx = np.empty(4)
    for i, x0 in enumerate([-2.20, -1.5, -0.7, 1.5]):
        xx[i], iters = solve(fvals_func, x0)
    yy = 1 - 0.6 * xx**2

    fig, ax = plt.subplots()
    ax.plot(x, x * np.cos(np.pi * x), 'r', label='$g_{1}(x)=sin(x)$')
    ax.plot(x, 1 - 0.6 * x**2, 'b', label='$g_{2}(x)=1-x^2$')
    ax.plot(xx, yy, 'ko', label='intersections')

    ax.set_xlim(-5, 5)
    ax.legend(loc='lower left')

    fig.savefig('intersections.png')
示例#8
0
def plot_intersections(fvals_func):
    x = np.linspace(-5, 5, 300)

    xx = np.empty(4)
    for i, x0 in enumerate([-2.20, -1.5, -0.7, 1.5]):
        xx[i], iters = solve(fvals_func, x0)
    yy = 1 - 0.6 * xx**2

    fig, ax = plt.subplots()
    ax.plot(x, x * np.cos(np.pi * x), 'r', label='$g_{1}(x)=sin(x)$')
    ax.plot(x, 1 - 0.6 * x**2, 'b', label='$g_{2}(x)=1-x^2$')
    ax.plot(xx, yy, 'ko', label='intersections')

    ax.set_xlim(-5, 5)
    ax.legend(loc='lower left')

    fig.savefig('intersections.png')
示例#9
0
def intersectionG(x0input):
    intersec = []
    xinter = []
    for x0 in x0input:
        x, iters = solve(f_val, x0, debug=False)
        print "solve returns x= %22.15e after %i iterations" % (x, iters)
        fx, fpx = f_val(x)
        g1vx, g1vx_p = g1val(x)
        print "The value of intersection is %22.15e" % fx
        if fx not in intersec:
            intersec.append(g1vx)
            xinter.append(x)

    xplot = linspace(-5., 5., 100.)
    g1 = xplot * cos(pi * xplot)
    g2 = 1. - 0.6 * xplot**2
    plt.plot(xplot, g1, 'b', xplot, g2, 'g', xinter, intersec, 'ro')
    plt.show()
示例#10
0
def main(debug = False):
    """
    Main function to show Newton Method to calculate intersections.
    """
    x = np.linspace(-5,5,100)
    y1 = [x1 * math.cos(x1 * math.pi) for x1 in x]
    y2 = 1 - 0.6*x**2

    plt.figure(1)
    plt.clf()
    plt.plot(x,y1,label='g1')
    plt.plot(x,y2,label='g2')

    guesses = [-2,-1.5,-0.8,1.5]
    for x0 in guesses:
        x,iter = solve(fvals,x0,debug)
        print 'With initial guess x0 = %22.15e' %x0
        print '\tsolve return x = %22.15e after %d iterations' %(x,iter)
        plt.plot(x,1 - 0.6*x**2,'k.')
    plt.legend(('g1','g2'))
    plt.show()
    plt.savefig('intersections.png') 
示例#11
0
def p4(debug_solve=False):
	"""
	Problem 4 from Week 3 HW, find intersects of two functions.
	"""
	from numpy import sqrt

	a_x = []
	a_fx = []

	for x0 in [-2.2, -1.6, -.75, 1.4]:
		print " "  # blank line
		# print "for init of the funcial guess %22.15e" % x0
		x,iters = solve(fvals_inter, x0, debug=debug_solve)
		print "solve returns x = %22.15e after %i iterations " % (x,iters)
		fx = f1(x)
		print "the value of f(x) is %22.15e" % fx

		# store values to plot
		a_x = np.append(a_x,x)
		a_fx = np.append(a_fx,fx)

	x_lin = np.linspace(-5,5,1001)
	pi = math.pi
	g1 = x_lin*np.cos(pi*x_lin)
	g2 = 1 - 0.6*x_lin**2
	plt.clf(); plt.plot(x_lin,g1,'r-',label='$g_1(x)$'); 
	plt.plot(x_lin,g2,label='$g_2(x)$')
	plt.legend()
	plt.plot(a_x, a_fx,'ko')

	plt.title("Intersections of $g_1(x)$ and $g_2(x)$")
	plt.legend()
	plt.savefig('intersections.png')

	if debug_solve:
		print "Intersection points (x,y)"
		for i in range(0,len(a_x)):
			print a_x[i], a_fx[i]
示例#12
0
def part(s, a):

    g = lambda x: arc(x) - s * arc(1)

    return solve(g, f, a, 0.5 * 10**-6)
示例#13
0
    """
    use four initial guess to solve the problem and then
    plot the figure as required
    """

    from newton import solve
    import matplotlib.pyplot as plt
    import numpy as np

    # initial guess by eyeballs
    guess = (-2.2, -1.5, -0.6, 1.5)
    x = np.ones(4)

    for i in range(4):
        print "\n*********************************************"
        x[i], iters = solve(fvals, guess[i], False)
        print "With initial guess x0 = %22.15e" % i
        print "solve returns x = %22.15e after %i iterations" % (x[i], iters)

    # plot figure
    xvals = np.linspace(-5, 5, 1000)
    g1 = xvals * np.cos(np.pi * xvals)
    g2 = 1 - 0.6 * xvals ** 2
    # for intersection point
    fx = x * np.cos(np.pi * x)

    plt.figure(1)  # open plot figure window
    plt.clf()  # clear figure
    plt.plot(xvals, g1)  # connect points with a blue line
    plt.plot(xvals, g2)
    plt.plot(x, fx, "ko")  # highlight intersection with black dots
def print_intersections(fvals_func):
    for x0 in [-2.20, -1.5, -0.7, 1.5]: # x0 taken looking at the plot
        x, iters = solve(fvals_func, x0)
        print('With initial guess x0 %20.15e,\n      solve returns x = %20.15e after %i iterations' % (x0, x, iters))
示例#15
0
Example use:
	>>> run intersections
"""

import newton
import matplotlib.pyplot as plt
import numpy as np

guesses = np.array([-2.2, -1.6, -0.8, 1.4])
xarray = np.zeros(4)
yarray = np.zeros(4)
i = 0

for xin in guesses:
    (xout, iters) = newton.solve(xin)
    xarray[i] = xout
    yarray[i] = (1 - (0.6 * xout**2))
    i = i + 1

x = np.linspace(-5, 5, 1000)

g1 = x * np.cos(np.pi * x)

g2 = (1 - (0.6 * x**2))

plt.figure(1)
plt.clf()
plt.xlim(-5, 5)
plt.xlabel('x (-)')
plt.ylabel('y (-)')
示例#16
0

def fvals(x):
    """
    f and f prime for this homework
    """
    #from numpy import pi,cos, sin
    f = (x * cos(pi * x)) - (1. - 0.6 * x * x)
    fp = (cos(pi * x) - pi * x * sin(pi * x)) - (-1.2 * x)
    return f, fp


xlist = []
for x0 in [-2.2, -1.5, -0.75, 1.5]:
    print " "  # blank line
    x, iters = solve(fvals, x0, debug=True)
    xlist.append(x)
    print "solve returns x = %22.15e after %i iterations " % (x, iters)
    fx, fpx = fvals(x)
    print "the value of f(x) is %22.15e" % fx

x0s = array(xlist)
x1 = linspace(-5., 5., 1000)
f1 = x1 * cos(pi * x1)
g1 = 1. - 0.6 * x1 * x1

plt.figure(1)  # open plot figure window
plt.clf()  # clear figure
plt.plot(x1, f1, 'r-')  # connect points with a blue line
plt.plot(x1, g1, 'b-')  # connect points with a blue line
# add intersections
示例#17
0
Example use:
	>>> run intersections
"""

import newton
import matplotlib.pyplot as plt
import numpy as np

guesses = np.array([-2.2, -1.6, -0.8, 1.4])
xarray = np.zeros(4)
yarray = np.zeros(4)
i = 0

for xin in guesses:
	(xout, iters) = newton.solve(xin)
	xarray[i] = xout
	yarray[i] = (1-(0.6*xout**2))
	i = i+1

x = np.linspace(-5,5,1000)

g1 = x*np.cos(np.pi*x)

g2 = (1-(0.6*x**2))

plt.figure(1)
plt.clf()
plt.xlim(-5,5)
plt.xlabel('x (-)')
plt.ylabel('y (-)')
示例#18
0
    g2x,g2px = g2(x)
    fx = g1x - g2x
    fpx = g1px - g2px
    return fx, fpx

# Points
xi = linspace(-5,5,1000)
g1xi, g1pxi = g1(xi)
g2xi, g2pxi = g2(xi)
fxi, fpxi = f(xi)

# Functions
plt.figure(1)
plt.clf()
plt.plot(xi, g1xi, 'b')
plt.plot(xi, g2xi, 'r')
plt.legend(['g1(x)=x*cos(pi*x)','g2(x)=1-0.6*x**2'])
plt.figure(1)

# Intersection points
for x0 in [-2.2, -1.6, -0.8, 1.45]:
    x,iters = solve(f, x0)
    print "\nWith initial guess x0 = %22.15e," % x0
    print "      solve returns x = %22.15e after %i iterations " % (x,iters)
    g1xi,g1pxi = g1(x)
    fxi,fpxi = f(x)
    print "    f(x) = %22.15e" % fxi
    plt.plot(x,g1xi,'ko')

plt.savefig('intersections.png')
示例#19
0
"""
from newton import solve
import numpy as np
from numpy import pi, cos, sin
import pylab

guesses = np.array([-2.15, -1.7, -.9, 1.3])
solns = np.zeros(4)


def fvals_intersect(x):
    """
    Return f(x) and f'(x) for f(x) = x*cos(pi*x)
	"""
    f = x * cos(pi * x) - 1 + 0.6 * x**2
    fp = -x * sin(pi * x) * pi + cos(pi * x) + 1.2 * x
    return f, fp


for j in range(len(guesses)):
    soln, i = solve(fvals_intersect, guesses[j])
    solns[j] = soln
    print 'With initial guess x0 = %22.15e,' % guesses[j]
    print '\tsolve returns x = %22.15e after %i iterations' % (soln, i)

#Begin Plotting
x = pylab.linspace(-5, 5, 1000)
fsolns = solns * cos(pi * solns)
pylab.plot(x, x * cos(pi * x), x, 1 - .6 * x**2, solns, fsolns, 'ko')
pylab.savefig('intersections.png')
    
xx = linspace(-10,10,1000)
g1xx,g1pxx = g1vals(xx)
g2xx,g2pxx = g2vals(xx)

plt.figure(1)
plt.clf()
plt.plot(xx,g1xx,'b')
plt.plot(xx,g2xx,'r')
plt.legend(['g1','g2'])

plt.figure(2)
plt.clf()
fxx,fpxx=fvals(xx)
plt.plot(xx,fxx,'b')
plt.plot(xx,0*xx,'k') # x axis
plt.title("plot of f(x)=g2(x)-g1(x)")

plt.figure(1)
for x0 in [-2.2,-1.6,-0.8,1.45]:
    x,iters = solve(fvals,x0)
    print "\nWith initial guess x0 = %22.15e, " % x0
    print "      solve returns x = %22.15e after %i iterations " % (x,iters)
    g1x,g1px = g1vals(x)
    fx,fpx = fvals(x)
    print "     f(x)=%22.15e" % fx
    plt.plot(x,g1x,'ko')
    
plt.axis((-5,5,-4,4))
plt.savefig('intersections.png')
    
示例#21
0
xx = linspace(-10, 10, 1000)
g1xx, g1pxx = g1vals(xx)
g2xx, g2pxx = g2vals(xx)

plt.figure(1)
plt.clf()
plt.plot(xx, g1xx, 'b')
plt.plot(xx, g2xx, 'r')
plt.legend(['g1', 'g2'])

plt.figure(2)
plt.clf()
fxx, fpxx = fvals(xx)
plt.plot(xx, fxx, 'b')
plt.plot(xx, 0 * xx, 'k')  # x-axis
plt.title("plot of f(x) = g2(x) - g1(x)")

plt.figure(1)
for x0 in [-2.2, -1.6, -0.8, 1.45]:

    x, iters = solve(fvals, x0)
    print "\nWith initial guess x0 = %22.15e," % x0
    print "      solve returns x = %22.15e after %i iterations " % (x, iters)
    g1x, g1px = g1vals(x)
    fx, fpx = fvals(x)
    print "    f(x) = %22.15e" % fx
    plt.plot(x, g1x, 'ko')

plt.axis((-5, 5, -4, 4))
plt.savefig('intersections.png')
示例#22
0
    f = g1(x) - g2(x)
    fp = np.cos(np.pi * x) + -1 * np.pi * x * np.sin(np.pi * x) + 1.2 * (x)
    return f, fp


if __name__ == "__main__":
    print "Running test..."
    x_guess = [-2, -1.6, -0.8, 1.4]
    xfinal = []

    plt.figure(1)
    plt.clf()
    x = np.linspace(-5, 5, 1000)
    y1 = g1(x)
    y2 = g2(x)
    g1plot, = plt.plot(x, y1, label=r"$xcos(\pi x)$")
    g2plot, = plt.plot(x, y2, label=r"$1-.6x^2$")

    for x0 in x_guess:
        print "With initial guess x0 = %22.16e " % x0
        (xf, i) = solve(fval_g1_g2, x0)
        print " \t solve returns x = %22.16e after %i iterations \n" % (xf, i)
        xfinal.append(xf)

    plt.plot(xfinal, map(g1, xfinal), 'ro', label='intersection')

    plt.grid()

    plt.legend()
    plt.savefig('intersections.png')
def g1(x):
    return x * cos(pi*x)

def g2(x):
    return 1 - .6*x**2

def g1g2(x):
    f = g1(x) - g2(x)
    fp = cos(pi*x) - x*pi*sin(pi*x) +  1.2*x
    return f, fp

##calculating the 4 zeros from the 4 initial guesses.
x_guesses = [-2.2,-1.6,-0.77,1.43]
zeros = []
for x0 in x_guesses:
    x, i = solve(g1g2, x0, False)
    zeros.append(x)
    print "With initial guess x0 = %22.15e," %x0
    print "      solve returns x = %22.15e after %i iterations" %(x,i)
    print

##plot the results
x = linspace(-5,5,500)
figure(1)
clf()
plot(x,g1(x))
plot(x,g2(x))
for i in range(4):
    plot(zeros[i],g1(zeros[i]),'ko')
savefig('intersections.png')
示例#24
0
	Returns g1(x) - g2(x) and g1'(x) - g2'(x)
	"""
	f = fvals_g1(x)[0] - fvals_g2(x)[0]
	fp = fvals_g1(x)[1] - fvals_g2(x)[1]
	return f, fp

### Set parameters
debug_solve = True
init_guess = [-2.5, -1.7, -1., 1.5]
pts_x = []
pts_y = []

### Solving for intersections
for x0 in init_guess:
	print " "
	x, iters = solve(fvals_f, x0, debug = debug_solve)
	print "With intial guess x0 = %22.15e," % x0
	print "		solve returns x = %22.15e after %i iterations " % (x,iters)
	fx = fvals_g1(x)[0]
	pts_x.append(x)
	pts_y.append(fx)

### Plotting two curves and intersection points
x = linspace(-5,5,1000)
y1 = fvals_g1(x)[0]
y2 = fvals_g2(x)[0]

figure(0)
clf()
plot(x, y1, 'b-', label = 'g1(x)')
plot(x, y2, 'r-', label = 'g2(x)')
示例#25
0
def print_intersections(fvals_func):
    for x0 in [-2.20, -1.5, -0.7, 1.5]:  # x0 taken looking at the plot
        x, iters = solve(fvals_func, x0)
        print(
            'With initial guess x0 %20.15e,\n      solve returns x = %20.15e after %i iterations'
            % (x0, x, iters))
import numpy as np
from newton import solve

x = np.linspace(-10, 10, 1000)
y1 = x * np.cos(np.pi * x)
y2 = 1 - 0.6 * (x * x)

plt.figure(1)
plt.clf()
plt.plot(x, y1, 'b-')
plt.plot(x, y2, 'r-')

def fun(x):
    f = x * np.cos(np.pi * x) - 1 + 0.6 * x**2
    fp = np.cos(np.pi * x) - x * np.sin(np.pi * x) * np.pi + 1.2 * x
    return f, fp

guesses = [-2.2, -1.6, -0.8, 1.4]
for x0 in guesses:
    print " "  # blank line
    x, iters = solve(fun, x0)
    print "solve returns x = %22.15e after %i iterations " % (x,iters)
    fx1 = x * np.cos(np.pi * x)
    fx2 = 1 - 0.6 * x**2
    print "the value of f(x) is %22.15e" % (fx1 - fx2)
    assert abs(fx1 - fx2) < 1e-14, "*** Unexpected result: x = %22.15e"  % x

    plt.plot(x, fx1, 'ko')

plt.savefig('intersections.png')
示例#27
0

def gdiffvals(x):
    """
    Differences betwen g1(x) and g2(x)
    """
    return g1vals(x)[0] - g2vals(x)[0], g1vals(x)[1] - g2vals(x)[1]


x0 = [-3.0, -2.0, -1.0, -0.5, 1.0, 2.0, 1.6]
xvals = np.zeros(len(x0))
yvals = np.zeros(len(x0))

for i in range(0, len(x0)):
    print " "
    x, iters = newton.solve(gdiffvals, x0[i], debug=False)
    xvals[i] = x
    yvals[i] = g1vals(x)[0]

    print "With initial guess x0 = %22.15e" % x0[i]
    print "      solve returns x = %22.15e after %s iterations" % (x, iters)
    print "        g1(x) - g2(x) = %22.15e" % gdiffvals(x)[0]

x = np.linspace(-5.0, 5.0, 1000)
y1 = g1vals(x)[0]
y2 = g2vals(x)[0]
plt.clf()
plt.plot(x, y1, "r-", x, y2, "b-", xvals, yvals, "ko")
plt.show()

plt.title("Intersections between g1(x) and g2(x)")
示例#28
0
import matplotlib.pyplot as plt


def fvals(x):
    """
    f and f prime for this homework
    """
    #from numpy import pi,cos, sin
    f = (x*cos(pi*x)) - (1. - 0.6*x*x)
    fp = (cos(pi*x) - pi*x*sin(pi*x)) - (-1.2*x)
    return f, fp 

xlist =[]
for x0 in [-2.2, -1.5, -0.75, 1.5]:
    print " "  # blank line
    x,iters = solve(fvals, x0, debug=True)
    xlist.append(x)
    print "solve returns x = %22.15e after %i iterations " % (x,iters)
    fx,fpx = fvals(x)
    print "the value of f(x) is %22.15e" % fx

x0s = array(xlist)    
x1 =  linspace(-5., 5., 1000)
f1 = x1*cos(pi*x1) 
g1 = 1. - 0.6*x1*x1

plt.figure(1)       # open plot figure window
plt.clf()           # clear figure
plt.plot(x1,f1,'r-')  # connect points with a blue line
plt.plot(x1,g1,'b-')  # connect points with a blue line
# add intersections
示例#29
0
of two known functions.
"""
from newton import solve
import numpy as np
from numpy import pi, cos, sin
import pylab

guesses = np.array([-2.15, -1.7,-.9,1.3])
solns = np.zeros(4)

def fvals_intersect(x):
	"""
    Return f(x) and f'(x) for f(x) = x*cos(pi*x)
	"""
	f = x*cos(pi*x) - 1 + 0.6*x**2
	fp = -x*sin(pi*x)*pi + cos(pi*x) +1.2*x
	return f, fp

for j in range(len(guesses)):
	soln, i = solve(fvals_intersect, guesses[j])
	solns[j]=soln
	print 'With initial guess x0 = %22.15e,' % guesses[j]
	print '\tsolve returns x = %22.15e after %i iterations' % (soln, i)


#Begin Plotting
x = pylab.linspace(-5,5,1000)
fsolns = solns*cos(pi*solns)
pylab.plot(x,x*cos(pi*x),x,1-.6*x**2,solns,fsolns,'ko')
pylab.savefig('intersections.png')
示例#30
0
xspace = linspace(-10,10,1000) 
g1x,g1px = g1vals(xspace)
g2x,g2px = g2vals(xspace)

#plot curves
plt.figure(1)
plt.clf()
plt.plot(xspace,g1x,'b')
plt.plot(xspace,g2x,'r')
plt.legend(['g1','g2'])

plt.figure(2)
plt.clf()
fx,fpx = fvals(xspace)
plt.plot(xspace,fx,'b')
plt.savefig('g2minusg1.png')

#plotting root points
plt.figure(1)
for x0 in [-2.2,-1.6,-0.8,1.45]:
  (x,i) = newton.solve(fvals,x0)
  print "\n Initial Guess: %22.15e" % x0
  print "   solve returned x = %22.15e after %i iterations "  % (x,i)
  g1xx,g1pxx = g1vals(x) # we could use g2 too
  fxx,fpxx = fvals(x)
  print " f(x) = %22.15e " %fxx
  plt.plot(x,g1xx,'ko')

plt.axis( (-5,5,-4,4) ) 
plt.savefig('inter.png')
示例#31
0
xspace = linspace(-10, 10, 1000)
g1x, g1px = g1vals(xspace)
g2x, g2px = g2vals(xspace)

#plot curves
plt.figure(1)
plt.clf()
plt.plot(xspace, g1x, 'b')
plt.plot(xspace, g2x, 'r')
plt.legend(['g1', 'g2'])

plt.figure(2)
plt.clf()
fx, fpx = fvals(xspace)
plt.plot(xspace, fx, 'b')
plt.savefig('g2minusg1.png')

#plotting root points
plt.figure(1)
for x0 in [-2.2, -1.6, -0.8, 1.45]:
    (x, i) = newton.solve(fvals, x0)
    print "\n Initial Guess: %22.15e" % x0
    print "   solve returned x = %22.15e after %i iterations " % (x, i)
    g1xx, g1pxx = g1vals(x)  # we could use g2 too
    fxx, fpxx = fvals(x)
    print " f(x) = %22.15e " % fxx
    plt.plot(x, g1xx, 'ko')

plt.axis((-5, 5, -4, 4))
plt.savefig('inter.png')