简体   繁体   中英

How was this percentage increase applied?

I wrote a conditional statement in Python which increases a price depending on the corresponding state's tax rate at the time.

In the example below, I set the purchase_amount to $17 and the state to CA. The tax rate is 7.5%. Here's is how I formulated it to get the correct answer of $18.275.

state = "CA"
purchase_amount = 17

if state == "CA":
    tax_amount = .075

elif state == "MN":
    tax_amount = .095

elif state == "NY":
    tax_amount = .085

total_cost = tax_amount * purchase_amount + purchase_amount

However, I saw someone use a different formulation, as seen below, to get the same exact answer.

if state == "CA":
    tax_amount = .075
    total_cost = purchase_amount*(1+tax_amount)

I have never seen a percentage applied this way before.

My MAIN QUESTION is...Where did the integer 1 even come from??

My second question is... Why was it added to the tax_amount before multiplying it by the purchase_amount?

This was especially alarming because while it is nice to have concluded with the same correct answer regardless, I aspire to adequately read the coding styles of others.

Thank you so much for your help!

Are you asking how to factor, like algebra 2 factoring. This would be called the distribution rule, the following lines are the same, by factoring out the common factor.

tax_amount * purchase_amount + purchase_amount

purchase_amount * ( tax_amount + 1 ) 

This is a math thing, if you want to add some % of the number to that number, you can do it two ways, your way:

(17 *.075) + 17 = 18.275

or their way:

17 * 1.075 = 18.275

these are both functionally the same calculation, just a different way of expressing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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