求方程的根二元搜索

2024-09-22 16:36:21 发布

您现在位置:Python中文网/ 问答频道 /正文

试图找出Python3.5的问题。这个程序是找到一个方程的根,一旦找到了围绕着0的两个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()

Tags: toanloinputreturnthatvaluedef