Lecture 5 numbers and built in functions


Published on

Published in: Technology, Business
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Lecture 5 numbers and built in functions

  1. 1. 1 of 45Module 5 : Numbers and Built‐in FunctionsIntroduction to       Computational ThinkingModule 5 :Numbers and Built‐in FunctionsAsst Prof Chi‐Wing FU, PhilipOffice: N4‐02c‐104email: cwfu[at]ntu.edu.sg
  2. 2. 2 of 45Module 5 : Numbers and Built‐in FunctionsTopics• More on Numbers• Built-in functions• Comparing floating point numbers• Case Study: Finding Square Root• Self Study: Bitwise operators (optional)
  3. 3. 3 of 45Module 5 : Numbers and Built‐in FunctionsMore on Numbers• Integers and Floating point numbers• Their representations in computers• Data range• Optional: Bitwise operators on integers
  4. 4. 4 of 45Module 5 : Numbers and Built‐in FunctionsMemory: Bits and Bytes• 1 Byte = 8 bits (each bit either 0 or 1)• 1 Byte has 28 different variations, i.e., 256• How about 4 bytes?00000000 0000111111111111100010011002Contents ofmemoryMemoryThis is also covered inIntroduction to Computing Systems
  5. 5. 5 of 45Module 5 : Numbers and Built‐in FunctionsIntegers (others)• In most programming languages, aninteger takes up 4 bytes. The first bit forsign: +ve or -ve, i.e., 31 bits left• Since there is a zero needed to berepresented (as all zeros in the 32 bits),the available data range is [-231, +231 – 1 ]
  6. 6. 6 of 45Module 5 : Numbers and Built‐in FunctionsIntegers (Python)• Integers in Python has unlimited precision• This is a useful feature in Python; otherwise,we (programmers) have to handle themourselves through programming effort
  7. 7. 7 of 45Module 5 : Numbers and Built‐in FunctionsFloat• For real numbers with decimals• Limited precision because we use limitednumber of bits to store the data in a specialformat (you will learn later in other course):• Max. representable finite float• Min. positive normalized floatWant to know more? http://docs.python.org/tutorial/floatingpoint.htmlhttp://en.wikipedia.org/wiki/Double_precision_floating-point_format
  8. 8. 8 of 45Module 5 : Numbers and Built‐in FunctionsFloat• and it has limited precision…• Hence, computation results with floatsmay not be exact
  9. 9. 9 of 45Module 5 : Numbers and Built‐in FunctionsInteger VS Float• When writing programs, variables that arenumeric can be integers or floats• So… how to choose?Think about the context!!!Need decimal values? Want precision?
  10. 10. 10 of 45Module 5 : Numbers and Built‐in FunctionsInteger VS Float• For the followings, which type ismore appropriate?• Age• Height• Volume of a container• Exchange rate• Voltage and current• Number of students in a class• Bank account balance
  11. 11. 11 of 45Module 5 : Numbers and Built‐in FunctionsTopics• More on Numbers• Built-in functions• Comparing floating point numbers• Case Study: Finding Square Root• Self Study: Bitwise operators (optional)
  12. 12. 12 of 45Module 5 : Numbers and Built‐in FunctionsWhat are Built-in functions• Built-in functions are subroutines, procedures,or methods that are built into Python itself; eachprovides a specific functionality• See the Python standard library:http://docs.python.org/library/functions.html• In fact, you knew some of them already:• print (for displaying data)• input (for reading user input)• float, int, str (for converting data)• type (for checking data type)• exec (for executing a string in Python), …, etc.
  13. 13. 13 of 45Module 5 : Numbers and Built‐in Functions• abs(x) – Return absolute value of x• min(x,y) and max(x,y) – Return minimumand maximum of x and y, respectivelyThey allow two ormore argumentsLet’s learn more: calling & arg(s)Takes one argument
  14. 14. 14 of 45Module 5 : Numbers and Built‐in FunctionsMore Built-in Functions• math.ceil(x) and math.floor(x) –Return the ceiling and floor of x as “int”Remember toimport math
  15. 15. 15 of 45Module 5 : Numbers and Built‐in FunctionsMore Built-in Functions• math.pow(x,y) – Return x raised to the power y• math.sqrt(x) – Return the square root of x• math.log(x) – Return natural logarithm of x• math.log10(x) – Return base-10 logarithm of xMath functionsusually return“float”
  16. 16. 16 of 45Module 5 : Numbers and Built‐in FunctionsMore Built-in Functions• math.sin(x), math.cos(x), math.tan(x)– Return the sine, cosine, and tangent of x (radian)• math.asin(x),math.acos(x),math.atan(x)– Return arc sin, cos, and tan of x in radian(Note: they all use radian!)• math.degrees(x) and math.radians(x)– Return x in degrees and radians, respectively
  17. 17. 17 of 45Module 5 : Numbers and Built‐in FunctionsHelp Function• help(“...”) – display help information on aPython function or module
  18. 18. 18 of 45Module 5 : Numbers and Built‐in FunctionsTopics• More on Numbers• Built-in functions• Comparing floating point numbers• Case Study: Finding Square Root• Self Study: Bitwise operators (optional)
  19. 19. 19 of 45Module 5 : Numbers and Built‐in FunctionsNo Equality!• If we want to know if two floating point numbersare equal or not, can we use "==" ??• It is tricky!!!They are not equal! Why?So… how to fix it?
  20. 20. 20 of 45Module 5 : Numbers and Built‐in FunctionsSo… how to check?• First, we can define a relatively small floatingpoint value, usually called epsilon or tolerance• IDEA: if the absolute difference between thetwo floating point numbers is smaller thanepsilon, we say that their values are the sameKey idea!!!!(computationally but not mathematically)
  21. 21. 21 of 45Module 5 : Numbers and Built‐in FunctionsTopics• More on Numbers• Built-in functions• Comparing floating point numbers• Case Study: Finding Square Root• Self Study: Bitwise operators (optional)
  22. 22. 22 of 45Module 5 : Numbers and Built‐in FunctionsCase Study• Here we want to implement an algorithm tocompute the square root of a value withoutusing math.sqrtYou should implement, run, and try the casestudy yourself in the course
  23. 23. 23 of 45Module 5 : Numbers and Built‐in FunctionsAlgorithm: compute square root• We can compute the square root of a value,say x, iteratively using the following idea:Given x,first compute an initial guess: guess = x/2then diff = guess* guess - xif abs(diff) < epsilon, we are doneif diff > 0, guess is too largeif diff < 0, guess is too smallupdate guess so that it gets closer, thenRepeat
  24. 24. 24 of 45Module 5 : Numbers and Built‐in FunctionsAlgorithm: compute square root• But… how to update guess so that it getscloser in every iteration…• Let’s check x/guess…In case x=100 and guess=50,x/guess = 2the targeting square root value should alwayslie between guess and x/guess!• So… we may update guess as mean value ofguess and x/guess and make it closer!
  25. 25. 25 of 45Module 5 : Numbers and Built‐in FunctionsAlgorithm: compute square rootLet’s do this test…• Iteration #1x=100 and guess=50x/guess=2 -> new guess = mean = 26• Iteration #2x=100 and guess=26x/guess=3.846 -> new guess = mean = 14.923• Iteration #3x=100 and guess=14.923x/guess=6.701 -> new guess = mean = 10.812…………Really getting closer and closer!!!
  26. 26. 26 of 45Module 5 : Numbers and Built‐in FunctionsImplementation• Here is the Python implementationWe will learn “while” in module 6.2
  27. 27. 27 of 45Module 5 : Numbers and Built‐in FunctionsImplementation• Add variable "iter" to count number of iterationsAdd iteration counter
  28. 28. 28 of 45Module 5 : Numbers and Built‐in FunctionsVerification… by math.sqrt• Lastly… we must verify our program!!!Report the differenceThis is a verification
  29. 29. 29 of 45Module 5 : Numbers and Built‐in FunctionsTesting #1• We try with x = 100Our resultDifference is very small
  30. 30. 30 of 45Module 5 : Numbers and Built‐in FunctionsTesting #2• We try with x = 100000Our resultBut…need moreiterations forlarger num.Differencestill small
  31. 31. 31 of 45Module 5 : Numbers and Built‐in FunctionsTesting #3• Lastly… try with x = 2Difference is still very smallFeweriterationsthis timeOur result
  32. 32. 32 of 45Module 5 : Numbers and Built‐in FunctionsTopics• More on Numbers• Built-in functions• Comparing floating point numbers• Case Study: Finding Square Root• Self Study: Bitwise operators (optional)
  33. 33. 33 of 45Module 5 : Numbers and Built‐in FunctionsWhat are Bitwise operators• Recall that integers are stored in binary, e.g.,
  34. 34. 34 of 45Module 5 : Numbers and Built‐in FunctionsNOT~SHIFT (right)>>SHIFT (left)<<Bitwise XOR^Bitwise OR|Bitwise AND&meaningoperatorWhat are Bitwise operators• Python provides bitwise operators that processinput integers bit by bit correspondingly• Treat 1 as true and 0 as falseInput:15 -> 0000 111117 -> 0001 0001What is 15 | 17 ?All are binaryoperations except ~,which is unary
  35. 35. 35 of 45Module 5 : Numbers and Built‐in Functions00 & 000 & 101 & 011 & 1ResultANDTruth tables of &, |, ^, ~00 | 010 | 111 | 011 | 1ResultOR00 ^ 010 ^ 111 ^ 001 ^ 1ResultXOR• XOR is called exclusive or; it is true ONLY if oneof the two bits is true (but not both)• ~x is a special operation called 2’s complement,which is just -x-1, i.e., ~2 gives -3
  36. 36. 36 of 45Module 5 : Numbers and Built‐in FunctionsExamples: &, |, ^&|^
  37. 37. 37 of 45Module 5 : Numbers and Built‐in FunctionsExamples: shift <<, >><<>>
  38. 38. 38 of 45Module 5 : Numbers and Built‐in Functions3 << 1 gives 6SHIFT (left)<<~3 gives -4NOT~3 >> 1 gives 1SHIFT (right)>>3 ^ 2 gives 1Bitwise XOR^3 | 2 gives 3Bitwise OR|3 & 2 gives 2Bitwise AND&examplesmeaningoperatorMore examplesTry to work them out yourself
  39. 39. 39 of 45Module 5 : Numbers and Built‐in FunctionsAny Application?1. Simple Data Encryption and Decryptionusing the xor operator2. Pseudo Random Number Generator(PRNG)
  40. 40. 40 of 45Module 5 : Numbers and Built‐in FunctionsApplication #1• xor can be used for doing simple encryptionand decryption• GivenD – our data (any integer, i.e., 32 bits)K – our key in encryption (which is an integer)• We can perform encryption by:E = D xor K where E is the encrypted integer• and decryption byE xor K gives DWe can recover D from E using KXOR has this interesting propertyWhy? Study the truth table…
  41. 41. 41 of 45Module 5 : Numbers and Built‐in FunctionsApplication #2• Pseudo Random Number Generator (PRNG):• Seed – A number to initialize the generator• Random number sequence – Use seed asinput, we apply the generator to obtain the firstrandom number; then use it as input togenerate the next random number, and so on…See http://docs.python.org/library/random.html• In designing a PRNG, bitwise operations areoften used, see next slide for a simple exampleInteresting article:http://spectrum.ieee.org/semiconductors/processors/behind-intels-new-randomnumber-generator
  42. 42. 42 of 45Module 5 : Numbers and Built‐in FunctionsApplication #2 (cont.)• Example: Define a function “parityOf” tocompute the parity of an integer:A bit to add to an integer to make thenumber of 1s in its binary form to be evenDefine a simple 12-bit PRNGA sequence of random number(binary numbers) can begenerated starting from the seednote: 0x indicateshexidecimal format
  43. 43. 43 of 45Module 5 : Numbers and Built‐in FunctionsApplication #2 (cont.)• Note:• You will learn how to use Python keyword “def” todefine functions later in this course• Using bitwise operators, we can efficiently compute theparity and develop pseudorandom number generators.There are many PRNGs in the world; some are morecomplicated, and they could have different quality…• Since the numbers generated in the example codeform a binary number sequence, we also call it aPseudo Random Binary Sequence Generator (PRBSG)• Related courses in the future:“Computer Organization and Architecture” and“Microprocessor-based System Design”
  44. 44. 44 of 45Module 5 : Numbers and Built‐in FunctionsTake Home Messages• Integers, Long, and Floating point numbers– Representation and property: data range, minimum andmaximum values, and precision• Built-in functions are useful resources built intoPython itself• Comparing floating point numbers can be tricky(and error-prone)– Use absolute difference against a small epsilon to testequality for floating point numbers
  45. 45. 45 of 45Module 5 : Numbers and Built‐in FunctionsReading Assignment• TextbookChapter 1: Beginnings1.8 to 1.10Note: Though some material (1.10) in textbook isnot directly related to the lecture material, you canlearn more from them.