Working with precedence

Consider the following formula, which multiples two variables and stores the result in a third variable called TaxYouOwe:


TaxYouOwe = NetIncome * TaxRate

Such a simple formula is easy to understand; you just multiply the values that both variables represent. Of course, you can create more powerful mathematical formulas by combining addition, subtraction, division, or multiplication, as in the following example:


TaxYouOwe = PastTaxes + NetIncome * TaxRate

If the value of PastTaxes is 2500, the value of NetIncome is 50000, and the value of TaxRate is 1.01, the computer looks at the formula as follows:


TaxYouOwe = 2500 + 50000 * 1.01

So now the question is what does the computer do first? Does it add 2,500 to 50,000 and then multiply the whole thing by 1.01 (in which case the answer is 53,025) or multiply 50,000 by 1.01 first and then add 2,500 (in which case the answer is 53,000)?

Because the result of combining addition, subtraction, division, and multiplication in a single formula can be so confusing, programming languages use something known as precedence, which tells the computer which mathematical operations to calculate first. Most programming languages calculate mathematical operators in the following order, from top (first) to bottom (last):

  •  Exponentiation (^)

  •  Multiplication (*) and division ( / )

  •  Integer division ( \)

  •  Modula arithmetic (mod)

  •  Addition (+) and subtraction (–)

Remember The computer always calculates operators from left to right if operators are equal in precedence, such as multiplication and division or addition and subtraction.

Before running the following Liberty BASIC program, try to figure out how the computer calculates a result:


MyMoney = 3 + 4 ^ 5 ? 8 / 5 * 7
PRINT MyMoney
END

This is how Liberty BASIC calculates the value of MyMoney:

  1. Because the computer calculates exponential values first, Liberty BASIC calculates the value of 4 ^ 5, which is 1024. The formula now looks like this:

    
    MyMoney = 3 + 1024 ? 8 / 5 * 7
  2. Next, the computer calculates all multiplication and division. Because multiplication and division have equal precedence, the computer starts calculating with the first multiplication or division operator that it finds,

    moving from left to right. The computer calculates the value of 8 / 5 first (1.6) and then multiplies it by 7. So the formula now looks like this:

    
    MyMoney = 3 + 1024 ? 11.2
  3. Finally, the computer calculates all addition and subtraction, moving from left to right. First it calculates the value of 3 + 1,024 (which is 1027), and then it subtracts 11.2 from 1027. Thus the final answer looks like this:

    
    MyMoney = 1015.8

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply



eXTReMe Tracker