import numpy as np import sys sys.path.append('/Users/lukewaldschmidt/ASTR119/modules') import opt_utils #defining function def f_1(x): return -x**5 + 1 / 3 * x**2 + 1 / 2 def f_2(x): return (np.cos(x))**2 + 0.1 def f_3(x): return np.sin(x / 3) + 0.1 * (x + 5) print opt_utils.my_Secant(f_1, .1, .2, tol=1e-4, N=20) # f1 has root at 0.157021404263 print opt_utils.my_Secant(f_2, 1, 1.1, tol=1e-4, N=20) # f2 has no roots, cos^2 + .1 never hits the x-axis print opt_utils.my_Secant(f_3, -1.2, -1.1, tol=1e-4, N=20) # f3 has a root at -1.1768780402
F2(x) = cos(x)**2 + 0.1 F3(x) = sin(x/3) + 0.1(x+5) """ import opt_utils as ou import numpy as np def f1_x(x, verbose=True): return -1 * x**5 + 0.333 * x**2 + 0.5 guess = -3 for x in range(-10, 10): ou.my_Secant(f1_x, guess, guess + 1, tol=1e-4) print("~~~~~~~~~ done F1(x) ~~~~~~~~~~") #the root is 0.9573 for F1(x) guess = 0 def f2_x(x): return np.cos(x)**2 + 0.1 for x in range(-3, 3): ou.my_Secant(f2_x, guess, guess + 1, tol=1e-4)
@author: scarletpasser """ import numpy as np import opt_utils ################################# A #################################### #function 1 def f_1(x): return -x**5 + (x**2) / 3. + 0.5 #interval for guess between 1 and 10, derivative equals 0 at x = 0 root_1 = opt_utils.my_Secant(f_1, 1, 10, tol=1e-4, N=20) print 'root 1: ', root_1 ################################# B #################################### #function 2 def f_2(x): return np.cos(x)**2 + 0.1 #this function never crosses the x - axis, secant methos returns infinity root_2 = opt_utils.my_Secant(f_2, -10, 10, tol=1e-4, N=20) print 'root 2: ', root_2
def f2(x): return np.cos(x)**2 + 0.1 def f3(x): return np.sin(x / 3) + 0.1 * (x + 5) #for x in range(x1min, x1max): # ou.my_Secant(f1, x1min, x1min + 0.1, tol=1e-4, N=20) # x += 1 #===================================================================================== #Find, print roots #===================================================================================== print ou.my_Secant(f1, x1min, x1min + 0.1, tol=1e-6, N=40), '<--------Root for a.' print ou.my_Secant(f2, x1min, x1min + 0.1, tol=1e-6, N=20), '<--------Root for b.' print ou.my_Secant(f3, x2min, x2min + 0.1, tol=1e-6, N=20), '<--------Root for c' #===================================================================================== """ Answers: a.) -0.057301 b.) No roots c.) -1.177 """
time3 = np.linspace(-3, 3, 1000) #------------------------------------------------------------------------------ # first function #------------------------------------------------------------------------------ def f1_x(x): return (-x**5 + (x**2) / 3. + 0.5) #plt.figure(1) #plt.plot(time1, f1_x(time1), 'ro', ms = 2) #plt.ylim(-1,1 ) #play with this range until the plot is precise #plt.show() root1 = opt_utils.my_Secant(f1_x, -1, 1) print('The root is: ', root1) #------------------------------------------------------------------------------ # second function #------------------------------------------------------------------------------ def f2_x(x): return (((np.cos(x))**2) + 0.1) #plt.figure(2) #plt.plot(time2, f2_x(time2), 'bo', ms = 2) #plt.show() root2 = opt_utils.my_Secant(f2_x, 0, 1.2)
# Secant Method calculations #======================================================= #defining steps, starting points, and create #an empty list for results to be stored p = 0 i = 0 N = 20 ini_x1 = -11 ini_x2 = -10 x_intcpt = [] x_intcpt.append(0.0001) #allows the while loop to pass the #iterations while i < N: #finding the roots using functions from opt_ utils root = utils.my_Secant(h_t, ini_x1, ini_x2) i += 1 ini_x1 += 1 #advancing from -10 to 10 ini_x2 += 1 if h_t(root) < 0.001: #filter out results that aren't roots if (root - x_intcpt[p]) / root < 0.01: #filter out repeated results pass else: p += 1 #adding the new result into the list x_intcpt.append(root) #and advance the list pass else: pass x_intcpt.remove(0.0001) #removing this element since it #has no more uses
This problem computes the roots for three functions using the Secant method. """ # a) import numpy as np import opt_utils # a) def f1(x): return -(x**5) + (x**2) / 3 + 0.5 f1_sec = opt_utils.my_Secant(f1, 1, 10, tol=1e-4, N=20) print "The root for f1 is at x =", str(f1_sec) # b) def f2(x): return np.cos(x)**2 + 0.1 #f2_sec = opt_utils.my_Secant(f2, -10, 10, tol = 1e-4, N = 20) """ There exists no root for y = (cos(x))^2 + 0.1 b/c fcm never crosses the x-axis. """
return -(x**5) + (x**2) / 3 + (1 / 2) def f2(x): return (np.cos(x))**2 + .1 def f3(x): return np.sin(x / 3) + .1 * (x + 5) #=================================================================================== # find roots #=================================================================================== # root calculation, set tol to 1e-6 for more precise results x_root1 = opt_utils.my_Secant(f1, x0, x0 + 10, tol=1e-6, N=20) x_root2 = opt_utils.my_Secant(f2, x0, x0 + 10, tol=1e-6, N=20) x_root3 = opt_utils.my_Secant(f3, x0, x0 + 10, tol=1e-6, N=20) print 'root of f1(x):', x_root1 print 'root of f2(x): none' # x_root2 does not exist print 'root of f3(x):', x_root3 #=================================================================================== # plots #=================================================================================== #These plots are here to help see what is a good x0 guess. a_x = np.linspace(xmin, xmax, 1000) plt.figure(1) ax = plt.subplot(311) ax.plot(a_x, f1(a_x), 'k-') plt.plot([xmin, xmax], [0, 0], 'r--')
return ((-x)**5) + (1 / 3) * x**2 + (1 / 2) def f2_x(x): return (np.cos(x))**2 + 0.1 def f3_x(x): return np.sin(x / 3) + 0.1 * (x + 5) t1 = np.linspace(-10, 10) t2 = np.linspace(-3, 3) for i in range(0, 20): x = opt.my_Secant(f1_x, .1, t1[i], tol=1e-4, N=20) i += 1 print('roots for 4a)', x) for i in range(0, 20): x1 = opt.my_Secant(f2_x, 0, t1[i], tol=1e-4, N=20) i += 1 print('roots for 4b)', x1) for i in range(0, 6): x2 = opt.my_Secant(f3_x, 0, t2[i], tol=1e-4, N=20) i += 1 print('roots for 4c)', x2)
@author: andreaskooi """ import numpy as np import opt_utils as ou def f1(x): return (-x**5) + ((x**2) / 3) + 0.5 def f2(x): return np.cos(x)**2 + 0.1 def f3(x): return np.sin(x / 3) + 0.1 * (x + 5) dx = 0.1 print("f1(t) has a root at ", ou.my_Secant(f1, 1, 1 + dx)) print("f2(t) has a root at ", ou.my_Secant(f2, 1, 1 + dx)) print("f3(t) has a root at ", ou.my_Secant(f3, -1, 1 + dx)) # Values # a. ) 0.957 # b. ) n/a # c. ) -1.17
# -*- coding: utf-8 -*- """ Created on Fri May 3 22:45:18 2019 """ import numpy as np import opt_utils as opt import math #=============================part a========================================== def f1(x): return -x**5 + (1 / 3) * x**2 + 1 / 2 f1 = opt.my_Secant(f1, -10, 10) print f1 #=============================part b========================================== def f2(x): return math.cos(x)**2 + 0.1 f2 = opt.my_Secant(f2, -10, 10) print f2 #=============================part c========================================== def f3(z): return math.sin(z / 3) + 0.1 * (z + 5)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # -10 < x < 10 for all functions x = np.arange( -10, 11) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # function 1 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #function 1 def f_1(x): return x**5 + (2*x**2)/5 - 2 #using my secant method, derivative = 0 at 0 so x0 > 0 root1 = opt_utils.my_Secant(f_1, 1, 2) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # function 2 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def f_2(x): return np.exp(-x/10) + x #using my secant method, function is pretty well behaves so bounds matter less root2 = opt_utils.my_Secant(f_2, -2, 5) #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # function 3 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# -*- coding: utf-8 -*- """ HOMEWORK 4 QUESTION 4 """ import math import opt_utils def f1_x(x): return -(x**5) + x**2 * (1.0 / 3.0) + 0.5 def f2_x(x): return math.cos(x)**2 + 0.1 def f3_x(x): return math.sin(x / 3.0) + 0.1 * (x + 5) for x in range(-10, 10): roots_f1 = opt_utils.my_Secant(f1_x, x, x + .1) roots_f2 = opt_utils.my_Secant(f2_x, x, x + .1) for x in range(-3, 3): roots_f3 = opt_utils.my_Secant(f3_x, x, x + .1) print 'f1 root(-10,10): ' + str(roots_f1) print 'f2 root(-10,10): ' + str(roots_f2) print 'f3 root(-3,3): ' + str(roots_f3)
#=============== Define Fct. ===============# def fct_1(x): return x**5 + 2. / 5 * x**2 - 2 def fct_2(x): return np.exp(-x / 10) + x def fct_3(x): return 10 * np.sin(x / 4) + 0.1 * (x + 12) #=============== Find Roots ===============# #using secant method from module/ data opt_utils f_Se_1 = opt_utils.my_Secant(fct_1, x0, x0 + 10, N=20) f_Se_2 = opt_utils.my_Secant(fct_2, x0, x0 + 10, N=20) f_Se_3 = opt_utils.my_Secant(fct_3, x0, x0 + 10, N=20) ax = np.linspace(xmin, xmax, 1000) plt.plot(ax, fct_1(ax), 'r-', label='f1(x)') plt.plot(ax, fct_2(ax), 'b-', label='f2(x)') plt.plot(ax, fct_3(ax), 'g-', label='f3(x)') plt.plot([xmin, xmax], [0, 0], 'k--') plt.plot([f_Se_1], [fct_1(f_Se_1)], 'k*', mfc='w', ms=10) plt.plot([f_Se_2], [fct_2(f_Se_2)], 'r*', mfc='w', ms=10) #plt.plot( [f_Se_3], [fct_3( f_Se_3)], 'r*', mfc = 'w', ms = 10) not needed/ does not land ofn the graphs plt.xlabel('t') plt.ylabel('Function Values') plt.ylim(-13, 14) plt.grid(True)
plt.figure(1) plt.ylabel('Function') plt.title('Roots of Three Functions') plt.legend() plt.subplot(221) plt.plot(time, f1_x(time), 'ro', ms=2) plt.ylim(-2.1, 1) #play with this range until the plot is precise plt.xlim(-2, 2) plt.plot(-1.0882465935220864, 0, 'ko') plt.xlabel('Time(s)') plt.ylabel('Function') plt.title('Roots of Three Functions') plt.legend() plt.show() root1 = opt_utils.my_Secant(f1_x, -2.1, -1.9) print('The root is: ', root1) #------------------------------------------------------------------------------ # second function #------------------------------------------------------------------------------ def f2_x(x): return (np.exp(-x / 10.) + x) plt.subplot(222) plt.plot(time, f2_x(time), 'bo', ms=2) plt.ylim(-1.5, 1.5) plt.xlim(-2, 2) plt.plot(-1.1183078051936663, 0, 'ko')
def f1 (x): return np.exp(-x/10) + x #setting parameters xmin,xmax = -10, 10 i = -10 N = 1 root = [] root.append(-20) #adding a number to kick start the loop a = 0 eps = 1e-3 while i < xmax: #looping with -10 to 10 and test out multiple intervels #print (i, i+N) #print root curr_root = opt.my_Secant(f1, i, i+N, N=30) if f1(i+N)-f1(i) <= eps: #filter out secant lines that doesn't cross the x-axis pass elif curr_root == None: #filter out results that doesn't work pass elif f1(curr_root) - f1(root[a]) < eps: #filter out similar results pass elif curr_root - root[a] > eps: #adding correct results to the list root.append(opt.my_Secant(f1, i, i+N)) a += 1 i += N root.remove(-20) #remove the useless variable a_root = np.asarray(root) #convert from list to array for calculation purpose print ('the root is at:', a_root)
xmin, xmax = -10, 10 x0 = 5 N = 20 err = 1e-5 #Define functions def f1(x): return x**5 + (2/5)*x**2 - 2 def f2(x): return np.exp(-x/10) + x def f3(x): return 10*np.sin(x/4) + 0.1*(x + 12) #Find roots fsec_1 = ou.my_Secant( f1, x0, x0 + 10, err, N) print fsec_1 fsec_2 = ou.my_Secant( f2, x0, x0 + 10, err, N) print fsec_2 fsec_3 = ou.my_Secant( f3, x0, x0 + 10, err, N) print fsec_3 #plot plt.figure() plt.subplot(111) ax = np.linspace( xmin, xmax, 1000) plt.plot( ax, f1( ax), 'k-', label = 'f1(x)') plt.plot( ax, f2( ax), 'g-', label = 'f2(x)') plt.plot( ax, f3( ax), 'r-', label = 'f3(x)')
def f2(x): return (np.cos(x)**2) + .1 #with -10 to 10 def f3(x1): return (np.sin(x1 / 3)) + (.1 * (x1 + 5)) # with -3 to 3 root1 = opt_utils.my_Secant(f1, -1, 1, tol=1e-7, N=100) root2 = opt_utils.my_Secant(f2, -10, 10, tol=1e-4, N=20) root3 = opt_utils.my_Secant(f3, -3, 3, tol=1e-4, N=20) plt.figure() p1 = plt.subplot(311) p1.plot(x, f1(x), 'r-') p1.plot([root1], [f1(root1)], 'r*', ms=15) p2 = plt.subplot(312) p2.plot(x, f2(x), 'b-') p2.plot([root2], [f2(root2)], 'b*', ms=15) p3 = plt.subplot(313) p3.plot(x1, f3(x1), 'k-') p3.plot([root3], [f3(root3)], 'k*', ms=15)
def fct1(x): return x**5 + (2 / 5) * x**2 - 2 def fct2(x): return np.exp(-x / 10) + x def fct3(x): return 10 * np.sin(x / 4) + 0.1 * (x + 12) #============================================================================= # ROOTS #============================================================================= secfct1 = utils.my_Secant(fct1, x0, x0 + 10, N=40) secfct2 = utils.my_Secant(fct2, x0, x0 + 10, N=40) secfct3 = utils.my_Secant(fct3, x0, x0 + 10, N=100) #============================================================================= # PLOTS #============================================================================= if testPlot == True: a_x = np.linspace(xmin, xmax, 1000) plt.figure(2) plt.plot(a_x, fct1(a_x), 'b-', label='f1(x)') plt.plot(a_x, fct2(a_x), 'g-', label='f2(x)') plt.plot(a_x, fct3(a_x), 'r-', label='f3(x)') plt.plot([xmin, xmax], [0, 0], '--') plt.plot([secfct1], [fct1(secfct1)], 'b*', mfc='w', ms=10) plt.plot([secfct2], [fct2(secfct2)], 'g*', mfc='w', ms=10)
return np.cos(x)**2 + 0.1 #defining steps, starting points, and create #an empty list for results to be stored p = 0 i = 0 N = 20 ini_x1 = -11 ini_x2 = -10 x_intcpt= [] x_intcpt.append(0.0001) #allows the while loop to pass the #iterations while i < N: #finding the roots using functions from opt_ utils root = utils.my_Secant(ft2, ini_x1, ini_x2) i += 1 ini_x1 += 1 #advancing from -10 to 10 ini_x2 += 1 #print ('attempts', i, ini_x1, ini_x2, root) if root == None: pass elif ft2 (root) < 0.001: #filter out results that aren't roots if (root-x_intcpt[p])/root < 0.01: #filter out repeated results pass else: p += 1 #adding the new result into the list x_intcpt.append(root) #and advance the list pass else: pass
# ============================================================================= # Define variables # ============================================================================= x1 = np.arange(-10., 11., 1.) # print(x1) # Unit testing import numpy as np x2 = np.arange(-3., 4., 1.) # print(x2) # Unit testing f1_root = opt.my_Secant(f_1, x1, x1 + 10.) f2_root = opt.my_Secant(f_2, x1, x1 + 10.) f3_root = opt.my_Secant(f_3, x2, x2 + 10.) for i in np.arange(0, 21, 1): if f1_root == x1[i]: print 'The roots of f1 are ', f1_root if f2_root == x1[i]: print 'The roots of f2 are ', f2_root if i < 20: i += 1 else: break for i in np.arange(0, 8, 1): if f3_root == x2[i]:
def fct2(x): return np.exp(-x / 10) + x def fct3(x): return 10 * np.sin(x / 4) + 0.1 * (x + 12) #=================================================================================== # find roots #=================================================================================== ## solve using secant method f_Se_x0 = ou.my_Secant(fct1, x0, x0 + 1, N=40) ## compare to python solutions: print('secant ----------- ', f_Se_x0, 'scipy: ', scopt.newton(fct1, x0, fprime=None)) f_Se_x02 = ou.my_Secant(fct2, x0, x0 + 1, N=40) ## compare to python solutions: print('secant ----------- ', f_Se_x0, 'scipy: ', scopt.newton(fct2, x0, fprime=None)) f_Se_x03 = ou.my_Secant(fct3, x0, x0 + 1, N=40) ## compare to python solutions: print('secant ----------- ', f_Se_x03, 'scipy: ', scopt.newton(fct3, x0, fprime=None)) ## test plot
def fx1(x): return (((-x)**5) + ((x**2) / 3.) + .5) def fx2(x): return ((np.cos(x))**2) + .1 def fx3(x): return ((np.sin(x / 3.)) + .1 * (x + 5)) a_fx1 = fx1(x) a_fx2 = fx2(x) a_fx3 = fx3(x) plt.subplot(211) plt.plot(x, a_fx1, 'r-') plt.subplot(212) plt.plot(x, a_fx2, 'g-') plt.plot(x, a_fx3, 'b-') root1 = opt.my_Secant(fx1, -5.0, 5.0, tol=1e-4, N=20) root2 = opt.my_Secant(fx2, -5.0, 5.0, tol=1e-4, N=20) root3 = opt.my_Secant(fx3, -5.0, 5.0, tol=1e-4, N=20) #print('the roots of f1(x) are %.3f.')%(root1) print('there are no roots of f2(x).') print('the roots of f3(x) are %.3f.') % (root3)
# root finding tol = 1e-6 #range of function t = np.linspace(xmin, xmax, 1000) #============================================================================== #Part a #============================================================================== def f1(x): return (x**5) + (2 / 5) * (x**2) - 2 ####find root of fn######## root1 = opt_utils.my_Secant(f1, x0, x0 + 10, N=40) print 'root of f1 is: ', root1 ############plotting###### plt.figure(1) plt.plot(t, f1(t), 'b-', label='f1(x)') plt.plot([root1], [f1(root1)], 'r*', mfc='w', ms=10, label=('Root: %.3f' % root1)) plt.plot([xmin, xmax], [0, 0], '--') plt.grid(True) plt.ylim(-10, 10) plt.xlabel('x') plt.ylabel('f1(x) value')
# numerical approx. of derivative dfdt = (fct(x1) - fct(x0)) / (x1 - x0) x_next = x1 - fct(x1) / dfdt x0 = x1 x1 = x_next print(i, 'fct_value', abs(fct(x1)), x_next) i += 1 # check is solution converged if abs(fct(x1)) > tol: return np.nan else: return x1 f_Se_x0 = opt_utils.my_Secant(f_1, x0, x0 + 10, N=40) print('secant ----------- ', f_Se_x0, 'scipy: ', scopt.newton(f_1, x0, fprime=None)) f_Se_x2 = opt_utils.my_Secant(f_2, x0, x0 + 10, N=40) print('secant ----------- ', f_Se_x2, 'scipy: ', scopt.newton(f_2, x0, fprime=None)) f_Se_x3 = opt_utils.my_Secant(f_3, x0, x0 + 10, N=40) print('secant ----------- ', f_Se_x3, 'scipy: ', scopt.newton(f_2, x0, fprime=None)) a_x = np.linspace(xmin, xmax, 1000) plt.plot(a_x, f_1(a_x), 'k-', label='f1(x)') plt.plot(a_x, f_2(a_x), 'g-', label='f2(x)') plt.plot(a_x, f_3(a_x), 'r-', label='f3(x)') plt.plot([xmin, xmax], [0, 0], '--') plt.plot([f_Se_x0], [f_1(f_Se_x0)], 'k*', mfc='w', ms=10)
df_dt = float(fct(x1) - fct(x0)) / (x1 - x0) x_next = x1 - fct((x1)) / df_dt print i, abs(fct(x1)), x_next x0 = x1 x1 = x_next # update variables at new step i += 1 if abs(fct(x1)) > tol: # no solution found return None else: return float(x_next) #------------------------------------------------------------------------- ## solve using secant method f_Se_x0 = opt_utils.my_Secant(fct1, x0, x0 + 10, N=40) ## compare to python solutions: print('secant ----------- ', f_Se_x0, 'scipy: ', scopt.newton(fct1, x0, fprime=None)) f_Se_x02 = opt_utils.my_Secant(fct2, x0, x0 + 10, N=40) ## compare to python solutions: print('secant ----------- ', f_Se_x0, 'scipy: ', scopt.newton(fct2, x0, fprime=None)) f_Se_x03 = opt_utils.my_Secant(fct3, x0, x0 + 2, N=40) ## compare to python solutions: print('secant ----------- ', f_Se_x03, 'scipy: ', scopt.newton(fct3, x0, fprime=None)) #==================================================================================
def f3(x): return 10 * np.sin(x / 4) + 0.1 * (x + 12) #============================================================================== # params #============================================================================== xmin, xmax = -10, 10 #starting point x0 = 5 #============================================================================== # find roots w/ Secant method #============================================================================== root1 = opt_utils.my_Secant(f1, x0, x0 + 2) root2 = opt_utils.my_Secant(f2, x0, x0 + 2) root3 = opt_utils.my_Secant(f3, 0, 1) #============================================================================== # plot #============================================================================== a_x = np.linspace(xmin, xmax, 1000) plt.figure(1) plt.title('root for first equation') plt.plot(a_x, f1(a_x), 'k', label='f(x)=x^5+2/5x^2-2') plt.plot(root1, f1(root1), 'r*', label='root at x=%f' % (root1)) plt.grid(True) plt.legend(loc='upper left') plt.xlabel('x')