Question

I was writing a formula in python to help me easily calculate the break even formula when trading stocks. The formula is to calculate the break even point is: ((shares x price)+commission)/(shares)

So for my python code I wrote:

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.

Can anyone tell me where I went wrong, thanks.

Was it helpful?

Solution

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. This is called truncated division. Floating point numbers don't do this, so you get 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

OTHER TIPS

You always convert the input to an int, that means it is irrelevant if the user enters a float, the program sees an 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. The reason for this is that the binary representation of float can for example not store 0.1 exactly, but only approximately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top