简体   繁体   English

Python中的收支平衡公式

[英]Break Even Formula in Python

I was writing a formula in python to help me easily calculate the break even formula when trading stocks. 我正在用python编写公式,以帮助我在交易股票时轻松计算收支平衡公式。 The formula is to calculate the break even point is: ((shares x price)+commission)/(shares) 计算收支平衡点的公式是: ((股数x价格)+佣金)/(股数)

So for my python code I wrote: 因此,对于我的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

However, when I run it I don't get the correct answer sometimes (usually when there is a decimal involved). 但是,当我运行它时,有时并没有得到正确的答案(通常是十进制)。 For example, when shares = 20, price = 8.88 and commission = 10, python gives me the answer as 8, but the correct answer is 9.38. 例如,当份额= 20,价格= 8.88和佣金= 10时,python给我的答案是8,但正确的答案是9.38。

Can anyone tell me where I went wrong, thanks. 谁能告诉我我哪里出问题了,谢谢。

The problem is that you are using integers instead of floating point (decimal) numbers. 问题是您使用的是整数而不是浮点数(十进制)。 The idea is that in integer division, 3/4 becomes 0 , as opposed to 0.75 . 这个想法是,在整数除法中, 3/4变为0 ,而不是0.75 This is called truncated division. 这称为截断分割。 Floating point numbers don't do this, so you get 3/4 = 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

You always convert the input to an int, that means it is irrelevant if the user enters a float, the program sees an int. 您总是将输入转换为int,这意味着如果用户输入浮点数,程序将看到int则无关紧要。 You need to change the calls to: 您需要将呼叫更改为:

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

And since stock related things are mission critical I recommend you use the decimal module which ensures 100% correct results, whereas usual floating point arithmetic may always contain small errors that can grow to big errors over time if you use them in further calculations. 而且由于与库存相关的事情对任务至关重要,因此我建议您使用decimal模块,以确保100%正确的结果,而常规的浮点算法可能始终包含小的错误,如果在以后的计算中使用它们,随着时间的流逝会逐渐变为大的错误。 The reason for this is that the binary representation of float can for example not store 0.1 exactly, but only approximately. 这样做的原因是,例如float的二进制表示形式不能精确存储0.1,而只能近似存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM