Computer are really good at maths. They do maths really quickly. Most of the maths that computers do is ordinary maths like we do. See? We are learning ...- How to perform mathematical operations using computers / programming
So that we can ...- Use familiar arithmetic operators - addition, subtraction, multiplication
- Apply the two types of division - real / float division and integer division
- Use exponentiation
- Use incrementation and decrementation operators
- Apply precedence rules and use brackets to alter them
- Use rounding and truncation in appropriate circumstances
- Use the DIV and MOD operations and describe their application in programming
OK - I know it may seem simple, but you need to know them. Some of these are Python specific.
A standard assignment operator (=) will perform only assignment,
not maths. However, there are a number of equivalent assignment operators which perform shorthand mathematical functions.Of these, undoubtedly the most important are the Add AND (incrementation) and the Subtract AND (decrementation) assignment operators. Incrementation means 'adding to'. Decrementation means 'subtracting from'. Incrementation and decrementation operations are often carried out in programming during loops to alter the value of a counter variable.Remember that you can only increment or decrement a variable that is already declared! (In fact, this is true of any of the assignment operators).
Some mathematical operators are more 'important' than others and take precedence over others. You will be familiar with this from your work in Maths. In Python, the precedence rules are ... Notice that there are certain operators which have the same precedence as each other and are evaluated from left to right in this list. As always, however, it is the brackets that have the ultimate precedence and are able to change the precedence of any expression they surround. Consider the following evaluation tree ...
RoundingLike rounding in Maths, Python allows you to round digits to certain decimal places using the `round()` function.>>> round(3.1415927,3) 3.142 TruncationTruncation is where you shorten a value by cutting off after a certain number of digits. This is the equivalent to rounding towards zero. There are two ways of performing truncation in Python.
Method 1 : String formatting>>> d = 3.1415927 >>> p = 3 >>> t = float('{:.{precision}s}'.format(str(d),precision=str(d).find('.')+1+p)) >>> print(t) 3.141 Method 2 : The multiply and divide method>>> d = 3.1415927 >>> p = 3 >>> t = float(int((d)*(10**p))/(10**p)) >>> print(t) 3.141Neither are ideal but they work! There isn't currently a built in method in Python to perform truncation. In practical terms, truncation can be used in quantisation like sound sampling.
There is one very common use for the modulo (%) operator. Find out what it is and try to give an example of it in use. HINT : Search for 'Use of modulo operator' in Google.
END OF TOPIC ASSESSMENT |