我的Python方程求解器无法求解分数

0 python integer loops equation

好的,所以我制作了一个小方程求解器来求解x.它适用于整数值,但每当我尝试求解分数时,它就会进入无限循环.这是我的代码:

print "Make the variable in your equation stand for x"
print
startingLimit=int(raw_input("What is the lowest estimate that your variable could possibly be?"))
print
wholeNumber=raw_input("Do you know if your variable will be a whole number or a fraction? Answer: yes/no")
if (wholeNumber== "yes"):
    print
    fraction= raw_input("Is it a decimal/fraction? Answer:yes/no")
    if (fraction=="yes"):
        print
        print "This program will only calculate up to the 2nd place to the right of the decimal"
        xfinder=float(0.01)
    else:
        xfinder=int(1)
else:
    xfinder=float(0.01)


leftEquation=raw_input("Enter your left side of the equation:")
print
rightEquation=raw_input("Enter the right side of the equation:")
print
amountSolutions=100

print

#solving

a=0
indivisualCount=0
count=0
x=float(startingLimit)
while (count!=amountSolutions):
    ifstuffleft=eval(leftEquation)
    ifstuffright=eval(rightEquation)
    if (ifstuffleft!=ifstuffright):
        x=float(x+xfinder)
        print x
    else:
        a=(a+1)
        count=count+1
        print "Solution",a,"=",x
        print
        x=float(x+xfinder)
Run Code Online (Sandbox Code Playgroud)

Eri*_*ric 5

if (ifstuffleft!=ifstuffright): 应该成为

if abs(ifstuffleft - ifstuffright) < tolerance:

tolerance您愿意接受的错误在哪里?

  • @Jonathon Reinhart,不要冒犯,但这看起来不像对OP的反应.至少给他一个python手册部分的链接:http://docs.python.org/2/tutorial/floatingpoint.对于user1624992,问题是如何在计算机内部处理浮点,表示使相等性测试成为几乎永远不会返回True的危险操作,这就是为什么程序陷入无限循环的原因 (2认同)