2012-12-02 58 views
0

好吧,所以我做了一個解決x的小方程求解器。它適用於整數值,但每當我嘗試解決分數問題時,它將進入無限循環。這裏是我的代碼:我的Python方程求解器不能求解分數

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) 

回答

5

if (ifstuffleft!=ifstuffright):應該成爲

if abs(ifstuffleft - ifstuffright) < tolerance:

哪裏tolerance是你願意接受

+0

這凸顯了OP需要了解如何浮點錯誤值存儲在計算機上。 –

+2

@Jonathon Reinhart,不要冒犯,但這看起來不像是對OP的有力迴應。至少給他一個鏈接到python手冊部分:http://docs.python.org/2/tutorial/floatingpoint。對於user1624992,問題在於如何在計算機內部處理浮點數,使得相等性測試成爲幾乎從不返回True的風險操作的表示,這就是爲什麼程序被卡在無限循環中 – EnricoGiampieri