2014-01-19 40 views
0

我正在Python中編寫一個公式,以幫助我在交易股票時輕鬆計算破解公式。其計算公式爲計算盈虧平衡點是:((股X價格)+提成)/(股)在Python中破解偶數公式

所以對於我的Python代碼,我寫道:

shares = int(input("How many shares did you purchase: ")) 
price = int(input("At what price did you buy: ")) 
commission = int(input("How much did you pay in commission: ")) 

break_even= ((shares*price)+commission)/(shares) 

print break_even 

然而,當我運行它有時候並沒有得到正確的答案(通常在涉及小數時)。例如,當份額= 20,價格= 8.88和佣金= 10時,python給我答案爲8,但正確的答案是9.38。

誰能告訴我我哪裏出錯了,謝謝。

回答

3

問題是您使用整數而不是浮點(十進制)數字。這個想法是在整數除法中,3/4變成0,而不是0.75。這稱爲截斷分裂。浮點數不這樣做,所以你得到3/4 = 0.75

shares = float(input("How many shares did you purchase: ")) 
price = float(input("At what price did you buy: ")) 
commission = float(input("How much did you pay in commission: ")) 

break_even= ((shares*price)+commission)/(shares) 

print break_even 
+0

天才!使用「float」而不是「int」純粹的天才! – ng150716

2

你總是輸入轉換爲int,這意味着如果用戶輸入的浮動是無關緊要的,程序看到一個int。您需要更改的電話:

price = float(input("At what price did you buy: ")) 
commission = float(input("How much did you pay in commission: ")) 

而且,由於股票有關的事情是關鍵任務,我建議你使用decimal模塊,保證100%正確的結果,而通常的浮點運算可以始終包含小的誤差,可以長如果你在進一步的計算中使用它們,那麼隨着時間的推移會出現大的錯誤其原因是浮點數的二進制表示可能不能精確地存儲0.1,但只能近似地存儲0.1。

+0

+1推薦'Decimal'。 – abarnert