Вы находитесь на странице: 1из 1

0001 // NEWTON RAPHSON

0002 // Finding the root of any given polynomial


0003
0004 // Algorithm
0005 // Given the function f(x), solve for the first derivative f'(x).
0006 // Assume an initial value for f(xi).
0007 // Repeat:
0008 // a. Substitute xi to the function f(xi) and f'(xi).
0009 // b. Solve for the next value of xi:
0010 // x(i+1) = xi - f(xi)/f'(xi)
0011 // c. Until abs(f(xi)) < e or abs(x(i+1) - xi) < e.
0012
0013 // EXAMPLE
0014 // polynomial = [ 1 5 -6]
0015 // test point = - 3
0016 // root = -6
0017
0018 funcprot(0); //INITIALIZE FUNCTIONS
0019
0020 // DERIVATIVE OF A POLYNOMIAL TEST FUNCTION
0021 function [newpoly]=derivativepoly(polynomial)
0022 terms = length(polynomial); //DETERMINE NUMBER OF TERMS
0023 base = terms - 1; //BASE TERM
0024 element = 1; //ELEMENT NUMBER
0025 while element ~= terms
0026 newpoly(1,element) = polynomial(1,element) * base;
0027 element = element + 1; //INCREMENT ELEMENT
0028 base = base - 1; //DECREMENT BASE TERM
0029 end
0030 endfunction
0031
0032 //POLYNOMIAL EVALUATION FUNCTION
0033 function [sumpoly]=evalpoly(polynomial, point)
0034 terms = length(polynomial); //DETERMINE NUMBER OF TERMS
0035 power = terms - 1; //HIGHEST POWER WOULD BE
0036 element = 1; sumpoly = 0; //INITIALIZE SUM = 0;
0037 while element ~= terms + 1
0038 base = point**power; //POWER OF THE VARIABLE
0039 sumpoly = sumpoly + polynomial(1,element) * base;
0040 element = element + 1; //INC ELEMENT
0041 power = power - 1; //DEC POWER
0042 end
0043 endfunction
0044
0045 // NEWTON'S METHOD OF ROOT FINDING MAIN PROG
0046 disp("NEWTON''S METHOD OF ROOT FINDING a.k.a Newton Raphson")
0047 polynomial = input("Enter polynomial coefficients: "); //ENTER POLYNOMIAL
0048 x = input("Enter test point: "); //TEST POINT
0049 root = evalpoly(polynomial,x); //FIRST EVALUATION
0050 newpoly = derivativepoly(polynomial); //FIRST DERIVATIVE
0051 while abs(root) > 10**-15 //LOOP STARTS UNTIL ROOT ~ 0
0052 num = evalpoly(polynomial,x) //NUMERATOR
0053 den = evalpoly(newpoly,x); //DENOMINATOR
0054 x = x - num/den; //NEW X
0055 root = evalpoly(polynomial,x); //EVALUATE NEW X
0056 end
0057
0058 disp(x, "One root is: ") //DISPLAY ROOT

Вам также может понравиться