Question

In: Advanced Math

Create a python code that calculates fixed point iteration method using a for loop.

Create a python code that calculates fixed point iteration method using a for loop.

Solutions

Expert Solution

Using scipy.optimize.fixed_point:

import scipy.optimize as optimize

def func(x):
    return -x**3+1

# This finds the value of x such that func(x) = x, that is, where
# -x**3 + 1 = x
print(optimize.fixed_point(func,0))
# 0.682327803828

The Python code defining fixed_point is in scipy/optimize/minpack.py. The exact location depends on where scipy is installed. You can find that out by typing

In [63]: import scipy.optimize

In [64]: scipy.optimize
Out[64]: <module 'scipy.optimize' from '/usr/lib/python2.6/dist-packages/scipy/optimize/__init__.pyc'>

Here is the code in scipy 0.7.0:

def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500):
    """Find the point where func(x) == x

    Given a function of one or more variables and a starting point, find a
    fixed-point of the function: i.e. where func(x)=x.

    Uses Steffensen's Method using Aitken's Del^2 convergence acceleration.
    See Burden, Faires, "Numerical Analysis", 5th edition, pg. 80

    Example
    -------
    >>> from numpy import sqrt, array
    >>> from scipy.optimize import fixed_point
    >>> def func(x, c1, c2):
            return sqrt(c1/(x+c2))
    >>> c1 = array([10,12.])
    >>> c2 = array([3, 5.])
    >>> fixed_point(func, [1.2, 1.3], args=(c1,c2))
    array([ 1.4920333 ,  1.37228132])

    See also:

      fmin, fmin_powell, fmin_cg,
             fmin_bfgs, fmin_ncg -- multivariate local optimizers
      leastsq -- nonlinear least squares minimizer

      fmin_l_bfgs_b, fmin_tnc,
             fmin_cobyla -- constrained multivariate optimizers

      anneal, brute -- global optimizers

      fminbound, brent, golden, bracket -- local scalar minimizers

      fsolve -- n-dimenstional root-finding

      brentq, brenth, ridder, bisect, newton -- one-dimensional root-finding

    """
    if not isscalar(x0):
        x0 = asarray(x0)
        p0 = x0
        for iter in range(maxiter):
            p1 = func(p0, *args)
            p2 = func(p1, *args)
            d = p2 - 2.0 * p1 + p0
            p = where(d == 0, p2, p0 - (p1 - p0)*(p1-p0) / d)
            relerr = where(p0 == 0, p, (p-p0)/p0)
            if all(relerr < xtol):
                return p
            p0 = p
    else:
        p0 = x0
        for iter in range(maxiter):
            p1 = func(p0, *args)
            p2 = func(p1, *args)
            d = p2 - 2.0 * p1 + p0
            if d == 0.0:
                return p2
            else:
                p = p0 - (p1 - p0)*(p1-p0) / d
            if p0 == 0:
                relerr = p
            else:
                relerr = (p-p0)/p0
            if relerr < xtol:
                return p
            p0 = p
    raise RuntimeError, "Failed to converge after %d iterations, value is %s" % (maxiter,p)

Related Solutions

Use the Fixed-Point Iteration Method to find the root of f ( x ) = x...
Use the Fixed-Point Iteration Method to find the root of f ( x ) = x e^x/2 + 1.2 x - 5 in the interval [1,2].
Write a python code which prints triangle of stars using a loop ( for loop )...
Write a python code which prints triangle of stars using a loop ( for loop ) Remember what 5 * "*" does The number of lines of output should be determined by the user. For example, if the user enters 3, your output should be: * ** *** If the user enters 6, the output should be: * ** *** **** ***** ****** You do NOT need to check for valid input in this program. You may assume the user...
For the equation e^x =x+2, (a) use the fixed point iteration method to determine its two...
For the equation e^x =x+2, (a) use the fixed point iteration method to determine its two roots to eight correct decimal places (you may need to write this equation in two different ways of x = g(x) in order to obtain these two roots); (b) numerically calculate the convergence rates for your converged iterations; (c) compare these numerical convergence rates with the theoretical conver- gence rates we presented in class (also see Theorem 1.6 on page 38 of the textbook).
Complete the following in syntactically correct Python code. Write a program, using a for loop, that...
Complete the following in syntactically correct Python code. Write a program, using a for loop, that calculates the amount of money a person would earn over a period of time if his or her salary is 1 penny for the first day, 2 pennies for the second day, 4 pennies for the third day, and continues to double each day. 1.      The program should ask the user for the number of days the employee worked. 2.      Display a table showing the salary...
Using Python, use the following list (Temperature = [56.2,31.8,81.7,45.6,71.3,62.9,59.0,92.5,95.0,19.2,15.0]) to: - Create a loop to iterate...
Using Python, use the following list (Temperature = [56.2,31.8,81.7,45.6,71.3,62.9,59.0,92.5,95.0,19.2,15.0]) to: - Create a loop to iterate through each of the elements in the temperature list. - Convert each element of this list to a Celsius temperature and then, for each valid temperature in the list, print out both the original Fahrenheit temperature and the Celsius equivalent in this format: "32 degrees Fahrenheit is equivalent with 0 degrees Celsius."
Important: please use python. Using while loop, write python code to print the times table (from...
Important: please use python. Using while loop, write python code to print the times table (from 0 to 20, incremented by 2) for number 5. Add asterisks (****) so the output looks exactly as shown below.   Please send the code and the output of the program. ****************************************************************** This Program Shows Times Table for Number 5 (from 0 to 20) Incremented by 2 * ****************************************************************** 0 x 5 = 0 2 x 5 = 10 4 x 5 = 20 6...
This is using Python, it is utilizing code from a Fraction class to create a Binary...
This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this. Instruction for Binary Class: Exercise 6.18: Design an immutable class BinaryNumber, in the style of our Fraction class. Internally, your only instance variable should be a text string that represents the binary value, of the form '1110100'. Implement a constructor that takes a string parameter that specifies the original binary value....
Using Python code create a program only with beginners code. You are taking online reservations at...
Using Python code create a program only with beginners code. You are taking online reservations at the The inn Ask for your client’s name and save in a variable Ask how many nights your client will be staying and save in a variable Room rental is $145 per night Sales tax is 8.5% Habitation tax is $5 per night (not subject to sales tax) Print out: Client’s name Room rate per night Number of nights Room cost (room rate *...
Code in python Write a while loop code where it always starts form 2. Then it...
Code in python Write a while loop code where it always starts form 2. Then it randomly chooses a number from 1-4. If the number 4 is hit then it will write “TP” if the number 1 is hit then it will write”SL”. It will rerun the program every time the numbers 1 and 5 are hit. The code should also output every single number that is randomly chosen. 2 of the same numbers can't be chosen back to back...
PYTHON PROGRAMMING Using tktinker, create a gui that surrounds the code below that has buttons and...
PYTHON PROGRAMMING Using tktinker, create a gui that surrounds the code below that has buttons and labels and an overall theme. # Meet the chatbot Eve print('Hi there! Welcome to the ChatBot station. I am going to ask you a series of questions and all you have to do is answer!') print(' ') print('Lets get started') #begin questions firstName = input('What is your first name?: ') lastName = input('What is your last name? ') print("Hi there, ", firstName + lastName,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT