CSC1015F – Python Chapter2 Michelle Kuttel [email protected].
CSC1015F – Chapter 3, Computing with Numbers
description
Transcript of CSC1015F – Chapter 3, Computing with Numbers
![Page 2: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/2.jpg)
Data Types Data can have many different types
Python is dynamically typed In a dynamically typed language, a variable is
simply a value bound to a name; the value has a type -- like "integer" or "string" or "list"
-- but the variable itself doesn't. x=“hello”x=2.5
In a statically typed language, the variable itself has a type
if you have a variable that's an integer, you won't be able to assign any other type of value to it later.
2
![Page 3: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/3.jpg)
The type function Tells you what type (or “class”) your data item
is. e.g.:>>> type(3)<type ’int’>>>> type(3.14)<type ’float’>>>>type(3+2.1j)<class 'complex'>
3
![Page 4: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/4.jpg)
The type function Tells you what type (or “class”) your data item
is. e.g.:>>> myInt = -32>>> type(myInt)<type ’int’>>>> myFloat = 32.0>>> type(myFloat)<type ’float’>
4
![Page 5: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/5.jpg)
Numeric Data TypesFor numbers we have two BASIC types: integers:
whole numbers with no fractional part
floating point number: numbers with fractional part WARNING: store only an approximation to real
numbers there is a limit to the precision, or accuracy, or the
stored values e.g. 10/3
5
![Page 6: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/6.jpg)
Checkpoint: Why are there two basic types for numbers?
6
![Page 7: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/7.jpg)
Checkpoint: Why are there two basic types for numbers? style:
an integer can’t be a floating point
efficiency: integer arithmetic is simpler, and therefore faster, than for
floating point numbers. If you don’t need a float, use an int
7
![Page 8: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/8.jpg)
Numeric Data TypesWe also have: Complex numbers
combination of real and imaginary components Both represented by floating-point numbers imaginary part denoted by ‘j’ e.g. 3+2.1j
8
![Page 9: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/9.jpg)
Python built-in numeric operators+ addition- subtraction* multiplication/ float division** exponentiation% remainderabs() absolute value// integer division
9
![Page 10: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/10.jpg)
Numeric operationsFor the most part, operations on floats produce
floats and operations on integers produce integers e.g. ….
However, division is a bit more interesting. the / operator ALWAYS returns a floatbecause dividing two ints can produce a float
10
![Page 11: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/11.jpg)
Numeric operationsFor the most part, operations on floats produce
floats and operations on integers produce integers e.g. ….
However, division is a bit more interesting. the / operator ALWAYS returns a floatbecause dividing two ints can produce a float
WHY IS THIS A GOOD IDEA?
11
![Page 12: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/12.jpg)
Why is this a good idea? Many computer languages, including Fortran,
C, C++, and Java (and Python pre version 3), interpret a division operation a/b as integer division, if both operands a and b are integers. ONLY IF either a or b is a real (floating-point)
number, DOES a/b implies the standard mathematical float division.
This confusion leads to one of the most common errors in mathematical software not at all obvious for a newcomer to programming.
Python 3 fixes this!
12
![Page 13: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/13.jpg)
Example: Temperature converter# convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Suzie Programmer
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/ 5 * celsius + 32
print "The temperature is", fahrenheit, "degrees Fahrenheit.”
main()
13
![Page 14: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/14.jpg)
Numeric operations to ensure an integer result, use //
truncating division operator also known as floor division
examples….
14
![Page 15: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/15.jpg)
CheckpointIn Python 3, the expression 10//3 will evaluate
as:a. 3.3333333333333333b. 3.3333333333333335c. 3d. 3.0
15
![Page 16: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/16.jpg)
CheckpointIn Python 3, the expression 10/3 will evaluate
as:a. 3.3333333333333333b. 3.3333333333333335c. 3d. 3.0
16
![Page 17: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/17.jpg)
CheckpointIn Python 3, the expression '10.0'*2 will
evaluate as:a. 20b. 20.0c. '10.010.0'd. Syntax error
17
![Page 18: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/18.jpg)
CheckpointIn Python 3, the expression -7//3 will evaluate
as:a. -2b. -3c. -2.3333333333333335d. -2.3333333333333333
18
![Page 19: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/19.jpg)
NOTE: Integer division of negative numbers Python (and Ruby) define integer division of or
by a negative number differently to C and Java.
e.g. -7//3 Java = -2 Python= -3
integer arithmetic is not as simple as it appears!
19
![Page 20: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/20.jpg)
CheckpointIn Python 3, the expression 8//3*2.0 will
evaluate as:1. 5.3333333333333332. 103. 44. 4.0
20
![Page 21: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/21.jpg)
Python Programming, 2/e21
Type Conversions We know that combining an int with an int
produces an int, and combining a float with a float produces a
float. What happens when you mix an int and float
in an expression?x = 5.0 + 2
What do you think should happen?
![Page 22: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/22.jpg)
Python Programming, 2/e22
Type Conversions For Python to evaluate this expression, it must
either convert 5.0 to 5 and do an integer addition, or convert 2 to 2.0 and do a floating point addition.
Converting a float to an int will lose information
Ints can be converted to floats by adding “.0”
![Page 23: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/23.jpg)
Python Programming, 2/e23
Explicit Type Conversion In mixed-typed expressions Python will
convert ints to floats.
Sometimes we want to control the type conversion. This is called explicit typing.
![Page 24: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/24.jpg)
Python Programming, 2/e24
Type Conversions>>> float(22//5)4.0>>> int(4.5)4>>> int(3.9)3
>>> round(3.9)
4
>>> round(3)
3
![Page 25: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/25.jpg)
Checkpoint: Explain in English what this program does
number = eval(input("Type in a number:\n") ) divisor = eval(input("What do you want to
divide by?")) intResult = number//divisor remainder = number%divisor print(number,"/", divisor, "=", intResult,
"remainder", remainder)
25
![Page 26: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/26.jpg)
Math library Python provides many other useful
mathematical functions in a special math library.
A library is just a module that contains some useful definitions
26
![Page 27: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/27.jpg)
Math libraryThe math functions operate on integers and
floats but do not work with complex numbers (a separate module – cmath - can be used to perform similar operations on complex numbers).
The return value of all functions is a float. All trigonometric functions assume the use of
radians.
27
![Page 28: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/28.jpg)
Math librarysin(x) Returns the sine of x. cos(x) Returns the cosine of x. tan(x) Returns the tangent of x. acos(x) Returns the arc cosine of x. asin(x) Returns the arc sine of x. atan(x) Returns the arc tangent of x.
degrees(x) Converts x from radians to degrees.
radians(x) Converts x from degrees to radians.
28
![Page 29: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/29.jpg)
Math library
exp(x) Returns e ** x. ceil(x) Returns the ceiling of x. floor(x) Returns the floor of x.
copysign(x,y) Returns x with the same sign as y. fabs(x) Returns the absolute value of x.
factorial(x) Returns xfactorial.hypot(x, y) Returns the Euclidean
distance,sqrt(x* x+ y* y). isinf(x) Return True if x is infinity.
29
![Page 30: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/30.jpg)
Math libraryisnan(x) Returns True if x is NaN. ldexp(x, i) Returns x* (2 ** i). log(x[, base]) Returns the logarithm of x to
the given base. If base is omitted, this function computes the natural logarithm.
log10(x) Returns the base 10 logarithm of x.pow(x, y) Returns x** y. sqrt(x) Returns the square root of x. trunc(x) Truncates x to the nearest integer
towards 0.
30
![Page 31: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/31.jpg)
Python Programming, 2/e31
Using the Math LibraryIn the textbook: writing a program to compute the roots of a
quadratic equation:
The only part of this we don’t know how to do is find a square root… but it’s in the math library.
2 4
2
b b acx
a
![Page 32: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/32.jpg)
Python Programming, 2/e32
Using the Math Library To use a library, we need to make sure this
line is in our program:import math
Importing a library makes whatever functions are defined within it available to the program.
![Page 33: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/33.jpg)
Python Programming, 2/e33
Using the Math Library To access the sqrt library routine, we need to
access it as math.sqrt(x)
Using this dot notation tells Python to use the sqrt function found in the math library module.
To calculate the root, you can dodiscRoot = math.sqrt(b*b – 4*a*c)
![Page 34: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/34.jpg)
Math Library
Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root?
![Page 35: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/35.jpg)
Python Programming, 2/e35
The Limits of Int >>> import math >>> math.factorial(100) 933262154439441526816992388562667004
90715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
>>>
Wow! That’s a pretty big number! And Python can handle it….. can Java?
![Page 36: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/36.jpg)
Python Programming, 2/e36
The Limits of Int What’s going on?
While there are an infinite number of integers, there is a finite range of ints that can be represented.
This range depends on the number of bits a particular CPU uses to represent an integer value.
Typical PCs use 32 bits.
![Page 37: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/37.jpg)
Python Programming, 2/e37
The Limits of Int Typical PCs use 32 bits
That means there are 232 possible values, centered at 0.
This range then is –231 to 231-1. We need to subtract one from the top end to account for 0.
In 32-bit, the largest number that can be stored is 2147483647
![Page 38: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/38.jpg)
Python Programming, 2/e38
The Limits of Int Can use floats, but then no longer get an
exact answer float(math.factorial(100)) 9.332621544394415e+157 lost after the 16th digit! float are approximations – the precision is fixed,
larger range
But 100! was fine ? how does it work in Python?
![Page 39: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/39.jpg)
Python Programming, 2/e39
Handling Large Numbers: Long Int Very large and very small numbers are
expressed in scientific or exponential notation.
1.307674368e+012 means 1.307674368 * 1012
Here the decimal needs to be moved right 12 decimal places to get the original number, but there are only 9 digits, so 3 digits of precision have been lost.
![Page 40: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/40.jpg)
Python Programming, 2/e40
Handling Large Numbers Python has a solution, expanding ints!
Python ints are not a fixed size and expand to handle whatever value it holds.
![Page 41: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/41.jpg)
Python Programming, 2/e41
Handling Large Numbers Newer versions of Python automatically
convert your ints to expanded form when they grow so large as to overflow.
to do mathematical operations, Python breakers the expanded int into smaller pieces
We get indefinitely large values (e.g. 100!) at the cost of speed and memory
There is NO free lunch (ever)!!
![Page 42: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/42.jpg)
More about libraries: random library Pseudo-random numbersimport random
randint(a,b) Returns a random integer, x, in the range a
<= x <= b.
random() Returns a random number in the range [0.0,
1.0).
42
![Page 43: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/43.jpg)
Example program: Kiddymaths2import random #do this to use functions in random
def test():
start,stop=1,10
start2,stop2=1,10
dividend = random.randint(start,stop)
divisor = random.randint(start2,stop2)
intResult = dividend // divisor
remainder = dividend % divisor
print(dividend,"/", divisor, "=", intResult, "remainder", remainder)
test()
43
![Page 44: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/44.jpg)
Improving “Kiddymaths”How do we ask the children for the answer and
check whether they are correct? Need SELECTION statements…
44
![Page 45: CSC1015F – Chapter 3, Computing with Numbers](https://reader035.fdocuments.in/reader035/viewer/2022062314/56813e76550346895da89581/html5/thumbnails/45.jpg)
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 South Africa License.
45