Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University.

Similar presentations


Presentation on theme: "CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University."— Presentation transcript:

1 CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: 432-6400 Email: yry@cs.yale.edu

2 2 Admin  PS7 m Questions? m If you want bonus points by performing a GuitarHero, please let me know soon  Project teaming due tonight m Please use the Google spreadsheet to add your team members; if you have a rough idea of your project, please write down, as it helps us in matching https://docs.google.com/spreadsheets/d/1M217U1WXrX smq7YL_gBLSJFH7I2Ca3EiAdBdsDCVY4M/edit?usp=sha ring

3 3 Recap: The Encapsulation Principle Client Methods Data/state/ behaviors Client should not see the internal state or behaviors Client can see only the external API Benefits  Consistency: so that it is impossible for others to "reach in" and directly alter another object's state  Flexibility: so that you can change the state representation or impl later without worrying about breaking others’code

4  Encapsulated data types. m Don't touch data and do whatever you want. m Instead, ask object to manipulate its data.  Lesson. Limiting scope makes programs easier to maintain and understand. Ask, Don't Touch "principle of least privilege" "Ask, don't touch."

5 5 Recap: Encapsulation/How r access modifiers enforce encapsulation  public members (data and methods: can be accessed from anywhere  private members: can be accessed from a method defined in the same class m Members without an access modifier: default private accessibility, i.e., accessible in the same package; otherwise, not accessible.

6 6 Class Diagram Coin - face : int + flip() : void + isHeads() : boolean + toString() : String Above is a class diagram representing the Coin class. “-” indicates private data or method “+” indicates public data or method class name attributes methods

7 7 Recap: StdDraw vs DrawingPanel  StdDraw: a Non-OO design m Benefits Hides OOP programming complexity (No objects) Simplifies programming by converting the native Java coordinate system (up-side down) to a more intuitive coordinate system Adds additional methods such as square, point m Potential issue Only 1 drawing surface in your program  DrawingPanel m OO design allowing multiple panels

8 8 Outline  Admin and recap  Defining classes o Motivation and basic syntax o Simple examples o The encapsulation principle o OOP examples o DrawingPanel objects vs StdDraw  Random objects vs Math.random

9 Static Math.random() method vs Random Objects 9

10 10 Math.random() Design r public static double random() m Returns a random number between 0 and 1 r Most static methods that we encountered are deterministic methods m deterministic method: given the same input parameter, gives the same output  But the random() method cannot be (why?)

11 11 A Little Peek into Random Number Generation r The random numbers generated by Java are actually pseudo-random numbers  Suppose you get a random number R n, the next time you call it to get R n+1, it returns: R n+1 = R n * 25214903917 + 11 it then converts to the right range to you ! r This method is proposed by D. H. Lehmer m in mathematical jargon, Java uses a type of linear congruential pseudorandom number generator r Implication: the previously returned random number must be remembered.

12 The Random class  A Random object generates random numbers as preceding slide  Class Random is found in the java.util package. import java.util.Random;  Example: Random rand = new Random(); // Default, seed by time int randomNumber = rand.nextInt(10); // 0-9 Method nameDescription Random(long seed) Create a random number using a seed (R 0 ) Random() Create a random number using a seed derived from time setSeed(seed) Initialize the random number generator nextInt( ) Returns a random integer in the range [0, max) in other words, 0 to max-1 inclusive nextDouble() Returns a random real number in [0.0, 1.0) Q: What is the state of a Random object?

13 Using Random Numbers r Example: to get a random number from 1 to 20 int n = rand.nextInt(20) + 1; // 1-20 inclusive r To get a number in arbitrary range [min, max] inclusive:.nextInt( ) + Where is ( - + 1 ) m Example: A random integer between 4 and 10 inclusive: int n = rand.nextInt(7) + 4;

14 14 Math.random() r public static double random() m When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random() m This new pseudorandom-number generator is used thereafter for all calls to this method. r http://docs.oracle.com/javase/7/docs/api/ja va/lang/Math.html#random()

15 15 How May Math.random() be Implemented? public class Math { private static Random rand; public static double random() { if (rand == null) rand = new Random(); return rand.nextDouble(); }.. } A static variable, also called a singleton. A delegation implementation pattern.

16 16 Advantage and Issue of Using Math.random() r Advantage m Hide object-oriented programming, simplifying programming (shorter program, no need to know seeds) r Issue  A single Random object: Every request for a random number is handled by one single random object, creating a bottleneck client 1 client 2 client 3 client 1 client 2 client 3

17 17 Outline  Admin and recap  Defining classes o Motivation and basic syntax o Simple examples o The encapsulation principle o OOP examples o DrawingPanel objects vs StdDraw o Random objects vs Math.random  Complex numbers and fractal graphics

18 18 Complex Numbers r A complex number (a + bi) is a quintessential mathematical abstraction m (a + bi) + (c + di) = a + c + (b + d) i m (a + bi) x (c + di) = ac - bd + (ad + bc)i r A main power of complex numbers comes from Euler’s formula a = 3 + 4i, b = -2 + 3i a + b = 1 + 7i a  b = -18 + i | a | = 5

19 19 Complex Numbers are Widely Used r Control theory and Laplace transforms r Quantum mechanics and Hilbert spaces r Fractals r Signal processing and Fourier analysis Antennas

20 20 A Complex Class r Design questions: m State: what field(s) do we need to represent the state of a complex number? Design 1 –re, a number representing the real part –im, a number representing the imaginary part Design 2 –r, a number representing the distance to origin –theta, a number representing the angle

21 21 A Complex Class r Design questions: m Behaviors: what are some common behaviors of a complex number? a Complex constructor, to set up the object A abs method, to return the distance (magnitude) a toString method, to return a string description of a complex number Mathematical operations such as +, -, * –a plus method to add current complex number with another complex number –a times method to multiply current complex number with another complex number –…–…

22 22 The Complex Class: Design Question public class Complex { private double re; private double im; public Complex(double real, double imag) { re = real; im = imag; } public ?? plus(Complex b) { … } … -What is the return type of plus? -Should plus change the state of the number, e.g., Complex c1 = new Complex(1, 1); Complex c2 = new Complex(2, 1); c1.plus(c2); // c1 changes to (3, 2)

23 23 The Consistency (Familiarity) Design Principle r Suppose a, b, and c are standard numbers (Complex numbers are numbers after all) m Does a + b (think a.+(b) ) change a? no m What is the return of a + b (think a.+(b))? The value of a + b so that we can write a + b + c r State (no)change and return type of plus public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); }

24 24 Complex.java public class Complex { double re; double im; public Complex(double real, double imag) { re = real; im = imag; } public String toString() { return re + " + " + im + "i"; } public double abs() { return Math.sqrt(re*re + im*im); } public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); } public Complex times(Complex b) { double real = re * b.re – im * b.im; double imag = re * b.im + im * b.re; return new Complex(real, imag); } constructor instance variables methods creates a Complex object, and returns a reference to it refers to b's instance variable

25 Immutability: Advantages and Disadvantages r Immutable data type. Object's state does not change once constructed. m Complex is an example of Immutable objects. String defined by Java is another example. r Advantages. m Avoid aliasing bugs. m Makes program easier to debug. m Limits scope of code that can change values. m Pass objects around without worrying about modification. r Disadvantage. New object must be created for every value.

26 26 A Simple Client public static void main(String[] args) { Complex a = new Complex( 3.0, 4.0); Complex b = new Complex(-2.0, 3.0); Complex c = a.times(b); System.out.println("a = " + a.toString() ); System.out.println("b = " + b.toString() ); System.out.println("c = " + c.toString() ); } % java TestClient a = 3.0 + 4.0i b = -2.0 + 3.0i c = -18.0 + 1.0i

27 27 A Complex Client: Mandelbrot Set r Mandelbrot set. A set of complex numbers.  Plot. Plot (x, y) black if z = x + y i is in the set, and white otherwise. r Can be used to model complex rugged shapes such as uneven clouds, contours of mountains, winding riverbeds, arts, … r No simple formula describes which complex numbers are in set. - Instead, described using an algorithm. http://users.math.yale.edu/mandelbrot/

28 28 A Complex Client: Mandelbrot Set Mandelbrot set. Is complex number z 0 in the set? Iterate z t + 1 = (z t ) 2 + z 0. If | z t | diverges to infinity, then z 0 is not in set; otherwise z 0 is in set. z = 1 + i not in Mandelbrot set z = -1/2 is in Mandelbrot set -1/2 + 0i0 -1/4 + 0i1 -7/16 + 0i2 -79/256 + 0i3 -26527/65536 + 0i4 -1443801919/4294967296 + 0i ztzt 5 t 1 + i0 1 + 3i1 -7 + 7i2 1 - 97i3 -9407 – 193i4 88454401 + 3631103i ztzt 5 t

29 29 Testing Point in Mandelbrot Set Practical issues. n Cannot iterate infinitely many times. Approximate solution. Fact: if | z t | > 2 for any t, then z not in Mandelbrot set. Pseudo-fact: if | z 255 | < 2 then z "likely" in Mandelbrot set.

30 30 Testing Point in Mandelbrot Set Our Mandelbrot test: Returns the number of iterations to check if z0 is in Mandelbrot public static int mand(Complex z0) { final int max = 255; Complex z = z0; for (int t = 0; t < max; t++) { if (z.abs() > 2.0) return t; z = z.times(z).plus(z0); } return max; } z = z 2 + z 0

31 31 Plotting Mandelbrot Set Practical issues. n Cannot plot infinitely many points. Display technique. n User specifies center, size Program maps the points on the N -by- N drawing panel to center, size x c + y c i (x c -size/2) + (y c -size/2) i Each grid has length size/N

32 32 Plotting Mandelbrot Set (DrawingPanel) Plot the Mandelbrot set in gray scale. public static void main(String[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); DrawingPanel panel = new DrawingPanel(N, N); Graphics g = panel.getGrahics(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/N; double y0 = yc - size/2 + size*j/N; Complex z0 = new Complex(x0, y0); int gray = mand(z0); Color color = new Color(gray, gray, gray); g.setColor( color ); g.drawLine(i, N-1-j, i, N – 1 - j); } // end of for } (0, 0) is upper left

33 33 Mandelbrot Set % java MandelbrotDrawingPanel –.5 0 2% java MandelbrotDrawingPanel.1045 -.637.01

34 34 Mandelbrot Set % java MandelbrotDrawingPanel –.5 0 2% java MandelbrotDrawingPanel.1045 -.637.01

35 35 Mandelbrot Set % java ColorMandelbrot –.5 0 2 Plot the Mandelbrot set in color using a color mapping table.

36 36 Mandelbrot Set % java ColorMandelbrot –.5 0 2 Plot the Mandelbrot set in color using a color mapping table.

37 37

38 38 Mandelbrot Set (-1.5, -1)

39 39 Mandelbrot Set  See video http://www.youtube.com/watch?v=cXM9J 77StL0

40 Picture Data Type r Raster graphics. Basis for image processing.  Set of values. 2D array of Color objects (pixels). r API.

41 41 Plotting Mandelbrot Set (Picture) Plot the Mandelbrot set in gray scale. public static void main(String[] args) { double xc = Double.parseDouble(args[0]); double yc = Double.parseDouble(args[1]); double size = Double.parseDouble(args[2]); Picture pic = new Picture(N, N); // NxN picture for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { double x0 = xc - size/2 + size*i/N; double y0 = yc - size/2 + size*j/N; Complex z0 = new Complex(x0, y0); int gray = mand(z0); Color color = new Color(gray, gray, gray); pic.set(i, N-1-j, color); } // end of for } scale to screen coordinates (0, 0) is upper left


Download ppt "CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University."

Similar presentations


Ads by Google