Im beginner at Python and I have a problem with this task:
- Write a function which find roots of user's mathematical function using fixed-point iteration.
- Use this function to find roots of:
x^3 + x - 1
. - Draw a graph of the dependence of roots approximation by the step number of iteration algorithm.
This is my first time using Python, so I really need help. This is my code, but its not working:
import math
import matplotlib.pyplot as plt
import numpy as np
def fixedp (function, x0, min = 0.001, max = 100):
i = 0
e = 1
xp = []
while (e > min and i < max):
x = function(x0)
e = norm(x0 - x)
x0 = x
xp.append(x0)
i = i + 1
return x, xp
fx = input("Wrote function : ")
function = lambda x: eval(fx)
x_start = 0.5
xf,xp = fixedp(function, x_start)
x = linspace(0,2,100)
y = function(x)
plot(x, y, xp, function(xp), 'bo', x_start, f(x_start), 'ro', xf, f(xf), 'go', x, x, 'k')
show()
First of all I will note the the logic of your code is great and working. There are some issues with indentation and syntax so I rewrote your code.
Good luck with Python in the future!