Example: Mean and Standard Deviation - NTUd00922011/java/254/20150725.pdf · Example: Mean and...

48
Example: Mean and Standard Deviation Write a program which calculates the sample mean and the sample standard deviation of any 3 numbers. Sample mean of three numbers is given by μ = 3 i =1 x i 3 . Also, the sample standard deviation is given by σ = s 3 i =1 (x i - μ) 2 2 . You may use these two methods: I Math.pow(double x, double y) for x y I Math.sqrt(double x) for x See more methods within Math class . Zheng-Liang Lu Java Programming 87 / 134

Transcript of Example: Mean and Standard Deviation - NTUd00922011/java/254/20150725.pdf · Example: Mean and...

Example: Mean and Standard Deviation

Write a program which calculates the sample mean and the samplestandard deviation of any 3 numbers.

Sample mean of three numbers is given by µ =

∑3i=1 xi3

.

Also, the sample standard deviation is given by

σ =

√∑3i=1(xi − µ)2

2.

You may use these two methods:I Math.pow(double x , double y) for xy

I Math.sqrt(double x) for√x

See more methods within Math class.

Zheng-Liang Lu Java Programming 87 / 134

1 ...2 public static void main (String[] args) {3 Scanner input = new Scanner(System.in);4 System.out.println("Enter a = ?");5 double a = input.nextDouble();6 System.out.println("Enter b = ?");7 double b = input.nextDouble();8 System.out.println("Enter c = ?");9 double c = input.nextDouble();

10 double mean = (a + b + c) / 3;11 a −= mean; // Deviation from mean12 b −= mean;13 c −= mean;14 double std = Math.pow(a,2) + Math.pow(b,2) + Math.pow(c,2);15 std /= 2;16 std = Math.sqrt(std);17 System.out.println("Mean = " + mean + "\n18 Standard Deviation = " + std);19 }20 ...

Zheng-Liang Lu Java Programming 88 / 134

Problem Set

Exercise 2.1 (Convert Celsius to Fahrenheit)

Write a program that reads a Celsius degree in a double value fromthe console, then converts it to Fahrenheit and displays the result.The formula for the conversion is as follows:

yF ◦ = (9

5)× xC ◦ + 32

Exercise 2.2 (Sum the digits in an integer)

Write a program that reads an integer between 0 and 1000 and addsall the digits in the integer. For example, if an integer is 932, thesum of all its digits is 14.

Zheng-Liang Lu Java Programming 89 / 134

Exercise 2.3 (Find the number of years)

Write a program that prompts the user to enter the minutes (e.g., 1billion), and displays the number of years and days for the minutes.For simplicity, assume a year has 365 days.

Exercise 2.4 (Heron’s formula.)

Write a program that prompts the user to enter three points(x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.

Zheng-Liang Lu Java Programming 90 / 134

Exercise 2.5 (Return rate)

Write a program that reads in investment amount X , future value ofinvestment Y , and number of years n, and displays the return rateof the investment r using the following formula:

r =n

√Y

X− 1.

Zheng-Liang Lu Java Programming 91 / 134

1 class Lecture3 {2

3 "Selections"4

5 }6

7 /∗ References8 [1] Ch. 3 in YDL9 ∗/

Zheng-Liang Lu Java Programming 92 / 134

Flow Controls

The basic algorithm or program constitutes the following operations:

Sequential operations: instructions executed in order.

Selective operations: first check if the condition is satisfied,then select the next instruction based on boolean values.

Repetitive operations: repeat the execution of a block ofinstructions until the criteria is not satisfied.

Zheng-Liang Lu Java Programming 93 / 134

Note that the three types of operations are not mutually exclusive.

In most cases, they are involved with each other.

For example, recall how to find the highest score of math quiz in theclass?

Zheng-Liang Lu Java Programming 94 / 134

Selections

Java has several types of selection statements:

one-way if statements

two-way if-else statements

nested if statements

switch-case statements

conditional expressions

Zheng-Liang Lu Java Programming 95 / 134

One-Way if Statements

A one-way if statement executes an action if and only if the conditionis true.

Zheng-Liang Lu Java Programming 96 / 134

1 if (condition) {2 // selection body3 }

The keyword if is followed by the parenthesized condition.

The condition should be a boolean expression or a boolean value.

It the condition is true, then the statements in the selection body willbe executed once.

If not, then the program won’t enter the selection body.

Note that the braces can be omitted if the block contains a singlestatement.

Zheng-Liang Lu Java Programming 97 / 134

Example

Write a program which receives a nonnegative number as input forthe radius of a circle, and determines the area of the circle.

1 ...2 if (radius >= 0) {3 area = radius ∗ radius ∗ 3.1415926;4 System.out.println("The area of the circle with radius " +5 radius + " is " + area + ".");6 }7 ...

But, the world is not well-defined.

Zheng-Liang Lu Java Programming 98 / 134

Two-Way if-else Statements

A two-way if-else statement decides which statements to executebased on whether the condition is true or false.

1 if (condition) {2 // selection body 13 }4 else {5 // selection body 26 }

Zheng-Liang Lu Java Programming 99 / 134

Zheng-Liang Lu Java Programming 100 / 134

Example

Write a program which receives a number as input for the radius of acircle. If the number is nonnegative, then determine the area of thecircle; otherwise, print “Not a circle.”

1 ...2 if (radius >= 0) {3 area = radius ∗ radius ∗ 3.1415926;4 System.out.println("The area of the circle with radius " +

radius + " is " + area + ".");5 }6 else {7 System.out.println("Not a circle.");8 }9 ...

Zheng-Liang Lu Java Programming 101 / 134

Example: Nested if Statements

An if statement can be inside another if statement to form a nestedif statement.

1 ...2 if (score >= 90) System.out.println("A");3 else {4 if (score >= 80) System.out.println("B");5 else {6 if (score >= 70) System.out.println("C");7 else {8 if (score >= 60) System.out.println("D");9 else System.out.println("F");

10 }11 }12 }13 ...

Zheng-Liang Lu Java Programming 102 / 134

Example: Multi-Way if-else

1 ...2 if (score >= 90) System.out.println("A");3 else if (score >= 80) System.out.println("B");4 else if (score >= 70) System.out.println("C");5 else if (score >= 60) System.out.println("D");6 else System.out.println("F");7 ...

An if-elseif-else statement is a preferred format for multiplealternatives, in order to avoid deep indentation and makes theprogram easy to read.

The order of conditions may be relevant. (Why?)

The performance may degrade due to the order of conditions. (Why?)

Zheng-Liang Lu Java Programming 103 / 134

Common Errors in Selection Statements

Two bugs?

1 ...2 if (r > 0);3 area = r ∗ r ∗ pi;4 System.out.println("Area = " + area);5 ...

How to revise in order to determine the maximum?1 ...2 int i = 1, j = 2, k = 3;3 if (i > j)4 if (i > k)5 System.out.println("Max = " + i);6 else if (j > k)7 System.out.println("Max = " + j);8 else9 System.out.println("Max = " + k);

10 ...

Zheng-Liang Lu Java Programming 104 / 134

Example

Generating random numbers

Write a program which generates 2 random integers and asks theuser to answer the math expression.

For example, the program shows 2 + 5 =?

If the user answers 7, then the program reports “Correct.” andterminates.

Otherwise, the program reports “Wrong answer. The correct answeris 7.” for this case.

You may use Math.random() for a random value between 0.0 and1.0, excluding themselves.

Zheng-Liang Lu Java Programming 105 / 134

1 ...2 public static void main(String[] args) {3

4 int x = (int) (Math.random() ∗ 10); // numbers 0 ˜ 95 int y = (int) (Math.random() ∗ 10);6

7 System.out.println(x + " + " + y + " = ?");8

9 Scanner in = new Scanner(System.in);10 int z = in.nextInt();11

12 if (z == (x + y))13 System.out.println("Correct.");14 else15 System.out.println("Wrong. The correct answer is " + (x + y

) + ".");16 in.close();17 }18 ...

Can you extend this program to include +−×÷ in the mathexpressions?

Zheng-Liang Lu Java Programming 106 / 134

Exercise

Find Maximum

Write a program which finds the maximum value in 3 random integerswhose range from 1 to 10.

How many variables do we need?

How to compare?

How to keep the maximum value?

Zheng-Liang Lu Java Programming 107 / 134

1 ...2 public static void main(String[] args) {3

4 int x = (int) (Math.random() ∗ 10 + 1);5 int y = (int) (Math.random() ∗ 10 + 1);6 int z = (int) (Math.random() ∗ 10 + 1);7

8 System.out.println("(x, y, z) = " + "(" + x + "," + y + "," + z+ ")");

9

10 int max = x;11 if (y > max) max = y;12 if (z > max) max = z;13 System.out.println("Max = " + max);14 }15 ...

In this case, a scalar variable is not convenient. (Why?)

Zheng-Liang Lu Java Programming 108 / 134

switch-case Statements

A switch-case statements executes statements based on the value ofa variable or an expression.

1 switch (target) {2 case value1:3 statements;4 break;5 case value2:6 .7 .8 case valuek:9 statements;

10 break;11 default:12 statements;13 }

Zheng-Liang Lu Java Programming 109 / 134

A switch-case statements is more convenient than an if statement tosimply the code for multiple discrete conditions.

target must yield a value of char, byte, short, int, or String type.

target must always be enclosed in parentheses.

value1,. . ., and valuek must have the same data type as the value oftarget.

In each case, a break statement is a must.1

The default case, which is optional, can be used to perform actionswhen none of the specified cases matches target.

1If not, there will be a fall-through behavior.Zheng-Liang Lu Java Programming 110 / 134

Example

Write a program which picks a day of week randomly.

How many discrete cases?

Zheng-Liang Lu Java Programming 111 / 134

1 public class weekday {2 public static void main(String[] args) {3 int day = (int) ((Math.random() ∗ 10) % 7 + 1);4 switch(day) {5 case 1:6 System.out.println("Monday");7 break;8 case 2:9 System.out.println("Tuesday");

10 break;11 case 3:12 System.out.println("Wednesday");13 break;14 case 4:15 System.out.println("Thursday");16 break;17 case 5:18 System.out.println("Friday");19 break;20 case 6:21 System.out.println("Saturday");22 break;23 case 7:24 System.out.println("Sunday");25 break;

Zheng-Liang Lu Java Programming 112 / 134

26 default:27 System.out.println("Invalid weekday?");28 }29 }30 }

Be aware that the arithmetic expression in Line 3 should beparenthesized. (Why?)

Zheng-Liang Lu Java Programming 113 / 134

Conditional Expressions

A conditional expression evaluates an expression based on a condition.

1 boolean expr ? expr A : expr B;

If the boolean expression is true, then the result is expr A; otherwise,expr B.

Zheng-Liang Lu Java Programming 114 / 134

For example,

1 ...2 if (num1 > num2)3 max = num1;4 else5 max = num2;6 ...

Alternatively, one can use a conditional expression like this:

1 ...2 max = (num1 > num2) ? num1 : num2;3 ...

Be aware that an extreme concise expression is not always good.2

2Recall the reason why we develop so many high-level programming languages.Zheng-Liang Lu Java Programming 115 / 134

Formatting Console Output

You can use System.out.printf () to display formatted output on theconsole.

1 ...2 double amount = 12618.98;3 double interestRate = 0.0013;4 double interest = amount ∗ interestRate;5 System.out.printf("Interest = %4.2f", interest);6 ...

Zheng-Liang Lu Java Programming 116 / 134

By default, a floating-point value is displayed with 6 digits after thedecimal point.

Zheng-Liang Lu Java Programming 117 / 134

Example: Multiple Items

Items must match the format specifiers in order, in number, and inexact type.

If an item requires more spaces than the specified width, the width isautomatically increased.

By default, the output is right justified.

You can put the minus sign (-) in the format specifier to specify thatthe item is left justified in the output within the specified field.

Zheng-Liang Lu Java Programming 118 / 134

Problem Set3

Exercise 3.1 (Roots of 2nd -order polynomials)

Write a program which solves y = ax2 + bx + c for all x , a, b, c ∈ Rusing the following formula:

x =−b ±

√b2 − 4ac

2a.

Note that a complex root and its conjugate are allowed in general.

Zheng-Liang Lu Java Programming 119 / 134

Exercise 3.2 (Game: scissor, rock, paper)

Write a program that plays the popular scissor-rockpaper game. Theprogram randomly generates a number 0, 1, or 2 representing scissor,rock, and paper. The program prompts the user to enter a number0, 1, or 2 and displays a message indicating whether the user or thecomputer wins, loses, or draws.

Zheng-Liang Lu Java Programming 120 / 134

Exercise 3.3 (Sort three integers)

Write a program that sorts three integers. The integers are enteredfrom the input dialogs and stored in 3 variables.

For example, the input is a = 1, b = 5, c = 2. Then the programdisplay the 3 numbers in ascending order, that is, 1 < 2 < 5.

Exercise 3.4 (Compute the perimeter of a triangle)

Write a program that reads three edges for a triangle and computesthe perimeter if the input is valid. Otherwise, display that the inputis invalid. The input is valid if the sum of every pair of two edges isgreater than the remaining edge.

Zheng-Liang Lu Java Programming 121 / 134

Exercise 3.5 (Geometry: points in triangle?)

Suppose a right triangle is placed in a plane as shown below. Theright-angle point is placed at (0, 0), and the other two points areplaced at (200, 0), and (0, 100). Write a program that promptsthe user to enter a point with x- and y-coordinates and determineswhether the point is inside the triangle.

Exercise 3.6 (Geometry: point in a circle?)

Write a program that prompts the user to enter a point (x , y) andchecks whether the point is within the circle centered at (0, 0) withradius 10.

Zheng-Liang Lu Java Programming 122 / 134

Exercise 3.7 (Game: pick a card)

Write a program that simulates picking a card from a deck of 52cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6,7, 8, 9, 10, Jack, Queen, King) and suit (Clubs, Diamonds, Hearts,Spades) of the card.

Exercise 3.8 (Finance: currency exchange)

Write a program that prompts the user to enter the exchange ratefrom currency in USD to TWD. Prompt the user to enter 0 to convertfrom USD to TWD and 1 to convert from TWD and USD. Promptthe user to enter the amount in USD or TWD to convert it to TWDor USD, respectively.

3See Programming Exercises in YDL, p. 121-131.Zheng-Liang Lu Java Programming 123 / 134

1 class Lecture4 {2

3 "Loops"4

5 }6

7 /∗ References8 [1] Ch. 5 in YDL9 ∗/

Zheng-Liang Lu Java Programming 124 / 134

Loops

A loop can be used to make a program execute statements repeatedlywithout having to code the same statements.

For example, a program prints “Hello, Java.” for 100 times.

1 System.out.println("Hello, Java.");2 System.out.println("Hello, Java.");3 .4 . // Copy and paste for 100 times5 .6 System.out.println("Hello, Java.");

Zheng-Liang Lu Java Programming 125 / 134

1 int cnt = 0;2 while (cnt < 100) {3 System.out.println("Hello, Java.");4 cnt++;5 }

This is a simple example to show the power of loops.

In practice, any routine which repeats couples of times4 can be doneby folding them into a loop.

4I’d like to call them “patterns.”Zheng-Liang Lu Java Programming 126 / 134

Flow Controls (Recap)

The concept of looping, which is one of elements in algorithms, isfundamental to programming.

Loops provide significant computation power.

Loops bring an efficient way of programming.

Loops could consume a lot of time.5

5We will visit the analysis of algorithms soon.Zheng-Liang Lu Java Programming 127 / 134

while Loops

A while loop executes statements repeatedly while the condition istrue.

1 ...2 while (condition) {3 // loop body4 }5 ...

The condition is a Boolean expression which controls the execution ofthe body.

It is evaluated each time to determine if the loop body is executed.

If true, the loop body is executed.

Otherwise, the entire loop terminates.

Zheng-Liang Lu Java Programming 128 / 134

Zheng-Liang Lu Java Programming 129 / 134

Example

Write a program which sums up all integers from 1 to 100.

In math, the question can be:

sum = 1 + 2 + · · ·+ 100.

But the form is not doable in a computer.I What is · · · ?!

Think in a programmer’s way.

Zheng-Liang Lu Java Programming 130 / 134

Normally, the computer executes the instructions sequentially.6

So, one needs to decompose the math equation into several lines, like:

1 int sum = 0;2 sum = sum + 1;3 sum = sum + 2;4 .5 .6 .7 sum = sum + 100;

Cons: Not efficient, not general (what if sum up to 1010?)

6If we are talking about the parallel computing, then it is a different world.Zheng-Liang Lu Java Programming 131 / 134

Using a while loop, the program looks like this:

1 ...2 int sum = 0;3 int i = 1;4 while (i <= 100) {5 sum = sum + i;6 ++i;7 }8 ...

Make sure that the condition eventually becomes false so that theloop will terminate.

It is really easy to make an infinite loop.

1 ...2 while(true);3 ...

Zheng-Liang Lu Java Programming 132 / 134

Besides, replacing 100 by n determined by the user makes thisprogram more general.

1 ...2 Scanner input = new Scanner(System.in);3 int n = input.nextInt();4 int sum = 0;5 int i = 0;6 while (++i <= n)7 sum = sum + i;8 ...

In practice, the number of loop steps is unknown until the input datais given.

For example, the bisection algorithm7 provides a numerical solution toroot-finding problems.

7http://en.wikipedia.org/wiki/Bisection_method

Zheng-Liang Lu Java Programming 133 / 134

Example

Write a program which sums two random integers and lets the userrepeatedly enter a new answer until it is correct.

1 ...2 public static void main (String[] args) {3 // random integer generation4 int number1 = (int)(Math.random() % 10);5 int number2 = (int)(Math.random() % 10);6

7 Scanner input = new Scanner(Sysmte.in);8 System.out.println(number1 + " + " + number2 + " = ?");9 int ans = input.nextInt();

10

11 while (number1 + number2 != ans) {12 System.out.println("Wrong answer. Try again?");13 ans = input.nextInt();14 }15 System.out.println("Congrats! You are smart!");16 }17 ...

Zheng-Liang Lu Java Programming 134 / 134