Python: Numbers and Arithmetic
Thursday 20th July 2017 2:55am
Addition and subtraction uses the same characters as used in mathematics i.e. + and – whereas division and multiplication uses / (forward-slash) and * (asterix) respectively. Use ** to multiply a value to the power of (exponent) and % to return the remainder of a value (modulo). If you supply a formula with integers (whole numbers) the result returned will be an integer, if you want to do calculations with decimal values then supply decimal values for example 20/100 = 0 whereas 20.0/100.0 = 0.2
>>> 1080 + 1920 # Addition 3000 >>> 1080 – 1920 # Subtraction -840 >>> 1080 * 1920 # Multiplication 2073600 >>> 1080/1920 # Division of integer 0 >>> 1080.0/1920.0 # Division of floating point 0.5625 >>> 2 ** 8 # Power (exponent) 256 >>> 8.75 % 0.5 # Modulo (remainder) 0.25 >>> 65536 / (8 * 8) # Nested Arithmetic 1024
Python stores decimal values in binary floating-point number format which can have some undesirable side effects.
>>> # Floating Point rounding error >>> 0.1 + 0.2 # Floating Point Addition 0.300000000000000004 # Should be 0.3 !!!???
Floating-Point Numbers.
To speed up calculations Python stores numerical values as binary floating point numbers and allocates 57 bits. A Floating Point number is a form of scientific notation so 300,000,000 could be represented as 3×10 to the power of 8 and 0.00000015 would be 1.5×10 to the power of minus 7. If we wanted to multiply these numbers together it would be much easier to multiply 3 by 1.5 and then add 10 to the power of 8 + 10 to the power of minues 7 or 8 minus 7 equals 1 therefore the answer = 4.5×10 to the power of 1 or 45. Now for the same reason that ⅓ cannot be represented in decimal without an infinite number of digits i.e. 0.33333… fractions cannot be represented absolutely accurately in binary floating point numbers.
As an example 0.1 * Base10 (decimal) = 1 with no remainder. If we do that same thing with binary we get a recurring number i.e. 0.1 * Base2 (binary) = 0 with remainder 2 using this remainder we 0.2 * Base2 = 0 remainder 4 and so on we will always have a remainder.
0.1 * 2 = 0.2 # 0 0.2 * 2 = 0.4 # 0 0.4 * 2 = 0.8 # 0 0.8 * 2 = 1.6 # 1 0.6 * 2 = 1.2 # 1 0.2 * 2 = 0.4 # 0 0.4 * 2 = 0.8 # 0 0.8 * 2 = 1.6 # 1 ...
So let’s see what 0.1 looks like in binary when truncated to 57 significant bits:
0.000110011001100110011001100110011001100110011001100110011001…
Bits 54 and beyond total to greater than half the value of bit position 53 thereby rounding up to:
0.0001100110011001100110011001100110011001100110011001101
In decimal this is:
0.1000000000000000055511151231257827021181583404541015625
Now if we round to 17 significant bits it would be 0.10000000000000001