我已经为割线方法编写了算法。代码在3.4中运行良好,但在2.7中它给出了str
和float
串联的错误。但是,通过使用str
函数,它不会给出连接错误,但会给出float
除法错误。
import random
import math
def secant(x, y, f):
count_iterations = 0
negligible_val = 0.000001
while abs(f(y)) > negligible_val:
z = x - ((y - x)/(f(y) - f(x))) * f(x)
x = y
y = z
count_iterations += 1
return y
x,y = random.uniform(0.1, 10.0), random.uniform(0.1, -10.0)
= input("Enter the function in brackets to find the roots: ")
#remember to put the input in the brackets
#example (x**3-x-11)
pars_text = "lambda x: " + str(input_func)
result = eval(pars_text)
roots = str(secant(x, y, result))
print("Roots are: " + roots)