@@ -0,0 +1,2372 @@
+#!/Applications/anaconda/envs/Python3/bin%0A%0Adef main():%0A    # X%5E2 - 1%0A    p_1 = (-1, 0, 1)%0A    r_1 = newton_raphson(p_1)%0A    print('Polynomial %7B%7D has root of %7B%7D'.format(print_poly(p_1), r_1))%0A%0A    # X%5E3 - 27%0A    p_2 = (-27, 0, 0, 1)%0A    r_2 = newton_raphson(p_2)%0A    print('Polynomial %7B%7D has root of %7B%7D'.format(print_poly(p_2), r_2))%0A%0A%0Adef print_poly(polynomial):%0A    '''%0A    Creates a string for a given polynomial, entered as a tuple of coefficients whee the index i of the item represents the power of the variable x.%0A    '''%0A    if polynomial%5B0%5D == 0:%0A        output = ''%0A    else:%0A        output = str(polynomial%5B0%5D)%0A%0A    for i, a in enumerate(polynomial):%0A        if a == 0 or i == 0:%0A            continue%0A        output = str(a) + 'x%5E' + str(i) + ' + ' + output%0A%0A    return output%0A%0A%0Adef eval_polynomial(polynomial, x):%0A    '''%0A    Inputs a tuple of coefficients a_i where the index i of the item represents the power of the variable x. Evaluates and returns the polynomial for given value of x.%0A    '''%0A    result = 0%0A    for i, a in enumerate(polynomial):%0A        result += a * (x ** i)%0A%0A    return result%0A%0A%0Adef compute_derivative(polynomial):%0A    '''%0A    Inputs a tuple of coefficients a_i where the index i of the item represents the power of the variable x. Returns a tuple in similar form that represents the derivative of the given polynomial.%0A    '''%0A    derivative = %5B%5D%0A    for a, i in enumerate(polynomial):%0A        derivative.append(i*a)%0A%0A    return tuple(derivative%5B1:%5D)%0A%0A%0Adef newton_raphson(polynomial, epsilon=0.01):%0A    '''%0A    General approximation to find the roots of a polynomial in one variable.%0A    p(x) = a_n * x%5En + a_n-1 * x%5En-1 + ... + a_1 * x + a_0%0A    Find r such that p(r) = 0%0A    If g is an approximation of the root, then g - p(g)/p'(g) is a better approximation, where p' is the derivative of p.%0A    Input is tuple of coefficients a_i where the index i of the item represents the power of the variable x%0A    '''%0A    guess = 1%0A    derivative = compute_derivative(polynomial)%0A    p_of_guess = eval_polynomial(polynomial, guess)%0A    d_of_guess = eval_polynomial(derivative, guess)%0A%0A    while abs(p_of_guess) %3E epsilon:%0A        guess = guess - (p_of_guess / d_of_guess)%0A        p_of_guess = eval_polynomial(polynomial, guess)%0A        d_of_guess = eval_polynomial(derivative, guess)%0A%0A    return guess%0A%0A%0Aif __name__ == '__main__':%0A    main()%0A

Add Newton-Raphson polynomial approximation problem