Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC1015F – Chapter 3, Computing with Numbers Michelle Kuttel

Similar presentations


Presentation on theme: "CSC1015F – Chapter 3, Computing with Numbers Michelle Kuttel"— Presentation transcript:

1 CSC1015F – Chapter 3, Computing with Numbers Michelle Kuttel mkuttel@cs.uct.ac.za

2 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

3 The type function  Tells you what type (or “class”) your data item is. e.g.: >>> type(3) >>> type(3.14) >>>type(3+2.1j) 3

4 The type function  Tells you what type (or “class”) your data item is. e.g.: >>> myInt = -32 >>> type(myInt) >>> myFloat = 32.0 >>> type(myFloat) 4

5 Numeric Data Types For 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

6 Checkpoint: Why are there two basic types for numbers? 6

7  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

8 Numeric Data Types We 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

9 Python built-in numeric operators +addition -subtraction *multiplication /float division **exponentiation %remainder abs()absolute value //integer division 9

10 Numeric operations For 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 float because dividing two ints can produce a float 10

11 Numeric operations For 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 float because dividing two ints can produce a float WHY IS THIS A GOOD IDEA? 11

12 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

13 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

14 Numeric operations  to ensure an integer result, use //  truncating division operator  also known as floor division  examples…. 14

15 Checkpoint In Python 3, the expression 10//3 will evaluate as: a. 3.3333333333333333 b. 3.3333333333333335 c. 3 d. 3.0 15

16 Checkpoint In Python 3, the expression 10/3 will evaluate as: a. 3.3333333333333333 b. 3.3333333333333335 c. 3 d. 3.0 16

17 Checkpoint In Python 3, the expression '10.0'*2 will evaluate as: a. 20 b. 20.0 c. '10.010.0' d. Syntax error 17

18 Checkpoint In Python 3, the expression -7//3 will evaluate as: a. -2 b. -3 c. -2.3333333333333335 d. -2.3333333333333333 18

19 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

20 Checkpoint In Python 3, the expression 8//3*2.0 will evaluate as: 1. 5.333333333333333 2. 10 3. 4 4. 4.0 20

21 Python Programming, 2/e 21 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?

22 Python Programming, 2/e 22 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 ”

23 Python Programming, 2/e 23 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.

24 Python Programming, 2/e 24 Type Conversions >>> float(22//5) 4.0 >>> int(4.5) 4 >>> int(3.9) 3 >>> round(3.9) 4 >>> round(3) 3

25 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

26 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

27 Math library The 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

28 Math library sin(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

29 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

30 Math library isnan(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

31 Python Programming, 2/e 31 Using the Math Library In 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.

32 Python Programming, 2/e 32 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.

33 Python Programming, 2/e 33 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 do discRoot = math.sqrt(b*b – 4*a*c)

34 Math Library  Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root?

35 Python Programming, 2/e 35 The Limits of Int  >>> import math  >>> math.factorial(100)  93326215443944152681699238856266700490715968264 38162146859296389521759999322991560894146397615 65182862536979208272237582511852109168640000000 00000000000000000  >>>  Wow! That ’ s a pretty big number!  And Python can handle it….. can Java?

36 Python Programming, 2/e 36 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.

37 Python Programming, 2/e 37 The Limits of Int  Typical PCs use 32 bits  That means there are 2 32 possible values, centered at 0.  This range then is – 2 31 to 2 31 -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

38 Python Programming, 2/e 38 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 16 th digit!  float are approximations – the precision is fixed, larger range But 100! was fine ?  how does it work in Python?

39 Python Programming, 2/e 39 Handling Large Numbers: Long Int  Very large and very small numbers are expressed in scientific or exponential notation.  1.307674368e+012 means 1.307674368 * 10 12  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.

40 Python Programming, 2/e 40 Handling Large Numbers  Python has a solution, expanding ints!  Python ints are not a fixed size and expand to handle whatever value it holds.

41 Python Programming, 2/e 41 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)!!

42 More about libraries: random library  Pseudo-random numbers import 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

43 Example program: Kiddymaths2 import 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

44 Improving “Kiddymaths” How do we ask the children for the answer and check whether they are correct?  Need SELECTION statements… 44

45  This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 South Africa License. 45


Download ppt "CSC1015F – Chapter 3, Computing with Numbers Michelle Kuttel"

Similar presentations


Ads by Google