teaching machines

CS 145 Lecture 5 – Math Cont’d

September 16, 2016 by . Filed under cs145, fall 2016, lectures.

Dear students,

Here’s something that happens. Your professor, who has been writing code for a long time, walks through many coding examples with you in class. He carefully arranges everything to present a coherent and compelling story, intentionally leading you into problems but swooping in with some new idea to save the day. You feel powerful, but then you get home and try to write some program of your own. But the only problems you’ve seen before have been your instructor’s cage-tamed problems—not your own. What happens when you breed your vicious strains of problems? Nobody knows, because those people have disappeared.

We can’t let that happen. We need to breed problems right here and now, in front of each other. So, today we start with an exercise:

Your kid brother comes up with what he thinks is an awesome Guess-a-Number game. He thinks of a number. You guess. He tells you how far away you are from the right answer. For example, suppose he picks the number 3, but you guess 10. He says you’re 7 away. In the real fake game, you guess again until you get it right. But let’s simulate just one guess in a fake fake version of this game using Java.

Simulate one guess of this game. Write a main method on paper. Let the computer be your brother, who picks the target number. It gets the human’s guess and reports how far the human is from the target.

Let’s continue exploring the methods that the Math class provides by solving some exercises that call upon it for help:

See you next class!


P.S. It’s Haiku Friday!

We’re wrong when we code
Wrong as a sculptor is wrong
At a ball of clay

P.P.S. Here’s the code we wrote together in class…


package lecture0916;

import java.util.Scanner;

public class Orangey {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Take a guess at what number I'm thinking of: ");
    int guess = in.nextInt();
    int lilbronum = (int) (Math.random() * 10);
    int distance = Math.abs(guess - lilbronum);
    System.out.println("You are " + distance + " away!");


package lecture0916;

import java.util.Scanner;

public class Lambert {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter angle: ");
    double degrees = in.nextDouble();
    double radians = Math.toRadians(degrees);
    double lightedness = Math.cos(radians);
    lightedness = Math.max(lightedness, 0);


package lecture0916;

public class CircleSpitter {
  public static void main(String[] args) {
    double originX = Math.random();
    double originY = Math.random();
    double edgeX = Math.random();
    double edgeY = Math.random();
    double radius = Math.hypot(edgeX - originX, edgeY - originY);
    System.out.printf("(x - %f) ^ 2 + (y - %f) ^ 2 = %f ^ 2", originX, originY, radius);