Chapter 3: Floating point Exercises

Find the errors in problems 1 through 8 and fix them if possible

1. if quarters > 0 then System.out.println(quarters + " quarters");
2. if (1 + x > Math.pow(x, Math.sqrt(2)) y = y + x;
3. if (x  =  1) y++;   else if  (x  =  2)   y  =  y  +  2;
4. if (x  && y  ==  0)   { x  =  1; y  = 1; }
5. if  (1 <=   X   <=  10) 
       System.out.println(x);
6. if (s !=  "nickels" || s  !=  "pennies"
      || s  !=  "dimes" || s  !=  "quarters")
      System.out.print("Input error!");
7. if (input.equalsIgnoreCase("N") || "NO")
      return;
8. int x  =  Integer.parseInt(input);
   if (x ! = null) y  =  y  +  x;
9. Write a truth table for the following boolean expressions and compare them: 

Complete the table below.
  p     q     r    (p && q) || !r     !(p && (q || !r))
  f     f     f
  f     f     t
  f     t     f
       ...
  5 more combinations

Programming Assignments:

1 . Write a program that reads in three floating-point numbers and prints the three inputs in sorted order. For example:

Please enter  three  numbers:
  4
  9
  2.5
The  inputs in sorted order are
  2.5
  4
  9

2. Write a Java program, CompareFloats_YI.java to show two floating-point numbers x and y such that Math.abs(x – y) is larger than 1000, but x and y are still identical except for a round­ off error.

Chapter 3: Comparing Characters – Strings – floating-point numbers

Chapter 3: More Notes

The switch Statement

Comparing Characters and Strings

if (ch1 > ch2)
   System.out.println (ch1 + " is greater than " + ch2);
else
   System.out.println (ch1 + " is NOT greater than " + ch2);


In the Unicode character set all lowercase alphabetic characters (‘a’ through ‘z’ ) are in alphabetical order. The same is true of uppercase alphabetic characters ( ‘A’ through ‘Z’ ) and digits ( ‘0’ through ‘9’ ). The digits come before the uppercase alphabetic characters,
which come before the lowercase alphabetic characters.

Assuming that namel and name2 are String objects

if (namel.equals(name2))
   System.out.println ("The names are the same.");
else
   System.out.println ("The names are not the same.");


int result = namel.compareTo(name2); 
if (result < 0)
   System.out.println (namel + " comes before II + name2); 
else
   if (result == 0)
      System.out.println ("The names are equal.");
   else
      System.out.println (namel + " follows" + name2);


Keep in mind that comparing characters and strings is based on the Unicode character set. This is called a lexicographic ordering. If all alphabetic characters are in the same case (upper or lower), the lexicographic ordering will be alphabetic.

However, when comparing two strings, such as “able” and “Baker”, the compareTo method will conclude that “Baker” comes first because all of the uppercase letters come before all of the lowercase letters Unicode character set.

A string that is the prefix of another, longer string is considered to precede the longer string. For example, when comparing two strings such as “horse” and “horsefly”, the compareTo method will conclude that “horse” comes first.

comparing floating point values

if (Math.abs(f1 - f2) < TOLERANCE)
   System.out.println ("Essentially equal.");         


The value of the constant TOLERANCE should be appropriate for the situation.

More Operators

Pre and Post unary operators

Increment: i++ and ++i
Decrement: i- – and – -i

Assignment Operator
assignments

Programming Project 3.3
Change the solution to the Programming Project 3.2 so that the user can enter more than one year. Let the user end the program by entering a sentinel value. Validate each input value to make sure it is greater than or equal to 1582.

Chapter 3: Comparing Floating Point Numbers

Comparing Floating-Point Numbers
Floating-point numbers have only limited precision, and calculations can introduce roundoff errors. Take a look at this example:

double r = Math.sqrt(2);
double d = r * r - 2;
if ( d == 0 )
   System.out.println(" sqrt(2) squared minus 2 is 0");
else
   System.out.println(" sqrt(2) squared minus 2 is not 0 but " + d);

When comparing floating-point numbers, don’t test for equality.
Instead, check whether they are close enough.
In Java, we program the test as follows: x is close to 0 if
Math.abs(x) ≤ EPSILON
where we define

final double EPSILON = 1E-14;

Similarly, you can test whether two numbers are close to each other by checking whether their difference is close to 0.
| x – y | ≤ ε
However, this is not always good enough. Suppose x and y are rather large, say a few billion each. Then they could be the same, except for a roundoff error, even if their difference was quite a bit larger than 10^(-14)
To overcome this problem, you need to divide by the magnitude of the numbers before comparing how close they are. Here is the formula: x and y are close enough if

     
      | x - y |
    ------------  ≤ ε
     max(|x|,|y|)

The choice of EPSILON depends on your application. Let’s take a look at one possible value:

final double EPSILON = 1E-14;
Math.abs( x - y ) / Math.max(Math.abs( x ), Math.abs( y )) <= EPSILON;

 
Assignments:

1. What EPSILON would you choose to find out if these two pair of values are relatively equal?
Show your calculations and how you determine if they are equal or not. This is dependent on the application. Justify your EPSILON.

Are 1,000,000 and 1,000,001 equal?
Are 0.0000002 and 0.0000003 equal?

Is there one EPSILON that fits all expressions?

2. Write a program, FloatCompare_YI.java that reads in two floating-point numbers and tests (a) whether they are the same when rounded to two decimal places and (b) whether they differ by less than 0.01. Here are two sample runs.
Enter two floating-point numbers:
2.0
1.99998
They are the same when rounded to two decimal places. They differ by less than 0.01.
Enter two floating-point numbers:
0.999
0.991
They are different when rounded to two decimal places. They differ by less than 0.01.

3. Write a program that prints all real solutions to the quadratic equation
ax² + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b² - 4ac is negative, display a message stating that there are no real solutions.
Implement a class QuadFormula_YI whose constructor receives the coefficients a, b, c of the quadratic equation. Supply methods getSolution1 and getSolution2 that get the solutions, using the quadratic formula.
Supply two methods

       boolean hasSolutions()

returns false if the discriminant is negative.

       boolean oneRealSolution()

returns false if the discriminant is negative. Implement this method using EPSILON to determine if discriminant is zero.

 

Chapter 2: Programming: Telephone Numbers with PDT and ADT

Chapter 2: Objects and Primitive Data Types

  1. Write a java application, TelephoneNumV1_YI.java that creates and prints a random phone number of the form XXX-XXX-XXXX. Include the dashes in the output. Do not let the first three digits contain an 8 or 9 (but don’t be more restrictive than that), and make sure that the second set of three digits is not greater than 742.
    Hint: Think through the easiest way to construct the phone number. Each digit does not have to be determined separately.

  2. Write an Object Oriented Application, TelephoneV2_YI.java with the same functionality as the previous version but using Object Oriented Design.

Chapter 2: Concepts Review

Concepts Review

  1. The information we manage in a Java program is either primitive data or ADT.
  2. An abstraction hides details. A good abstraction hides the right details at the right time.
  3. A variable is a name for a memory location used to hold a value of a particular data type.
  4. A variable can store only one value of its declared type.
  5. Java is a strongly typed language. Each variable has a specific type, and we cannot assign a value of one type to a variable of another type.
  6. Constants are like variables, but they hold one particular value.
  7. Java has two kinds of numeric values: integers and floating point. The primitive type int is an integer data type and double is a floating point data type.
  8. Many programming statements involve expressions. Expressions are combinations of one or more operands and the operators used to per­ form a calculation.
  9. Java has rules that govern the order in which operators will be evalu- ated in an expression.
  10. Avoid narrowing conversions because they can lose information.
  11. The new operator returns a reference to a newly created object.
  12. The Java standard class library is a useful set of classes that anyone can use when writing Java programs.

Submit answers to the following questions:
1. What is the content of an object variable?
2. Write a code snipped to compare two strings, s1 and s2. If s1 comes first in the lexicographic order, then it will print “move two steps forward” else “move two steps backwards.
3. Why the “= =” cannot be used to compare objects?
4. Give an example of widening and narrowing type conversion for each.
5. What is the purpose of casting when using a casting operator in the case of narrowing type conversion.
6. What is the result of 21 % 6 when evaluated in a java expression?
7. What is the result of (double) (15/2) in a java expression?
8. What does the operator new do?
9. Write the statement to print “Hello World” including the quotes.
10. What does “123456789”.substring(3,6) return?
11. Write a main method that prompts the use for two numbers, x and y, and it displays it back the following format: (x,y).

Chapter 2: Do programming assignments 2.13, 2.14 and 2.15 but instead of an applet write an application. You can use the university libraries or the java graphics libraries. The assignments are at the end of the chapter.
Screen Shot 2014-09-09 at 10.13.27 PM

screen-shot-2016-09-19-at-5-25-49-pm

Homework:
Read/browse pages 58 through 79

Computer Number Systems

Computer Number Systems

All computers – from large mainframes to hand-held micros – ultimately can do one thing: detect whether an electrical signal is “on” or “off”. Computer programs in BASIC and Pascal are converted by various pieces of systems software into sequences of bits (Binary digITs) which correspond to sequences of on/off (equivalently TRUE/FALSE or 1/0) signals. Proficiency in the binary number system is essential to understanding how a computer works.

Number Systems

Project: NBody Simulation

May 15th, 2015

Screen Shot 2015-05-12 at 11.47.35 AM

Using PU Classes:
Programming Assignment due on 5/29: N-Body Simulation
Screen Shot 2015-05-13 at 1.47.10 PM

Checklist

Some cool links:
Screen Shot 2015-05-13 at 1.54.01 PM

Screen Shot 2015-05-13 at 1.55.27 PM

Screen Shot 2015-05-13 at 1.57.08 PM


Some math and little bit of physics: