寻找方程的根源 - 二元搜索

时间:2016-10-27 16:27:48

标签: python python-3.x binary-search

尝试识别Python 3.5的问题。一旦找到围绕零的两个x值(一个产生正值而另一个产生负值),程序将找到方程的根。我想我有一个无限循环:

from math import *

def getFunction():
    func = input("Enter your function: f(x) = ")
    return func

def getHighLow():
    hi = eval(input("Enter an x-value that gives a positive result: "))
    lo = eval(input("Enter an x-value that gives a negative result: "))
    return hi, lo

def findTheZero(func, hi, lo):
    delta = eval(input("How close to zero to you want to get? Within 0.01 Enter a value: "))
    x = (hi + lo) / 2
    while abs(eval(func)) > delta:
        if x > 0:
            hi = x
            x = (hi + lo) / 2
        else:
            lo = x
            x = (hi + lo)/2
    return x

def main():
   function = getFunction()
   hi, lo = getHighLow()
   print(findTheZero(function, hi, lo))

main()

0 个答案:

没有答案