RU beehive logo ITEC dept promo banner
ITEC 120
2012fall
dbraffitt
ibarland

homeinfolectslabsexamshws
tutor/PIsbreeze (snow day)
Object120 + its docsjava.lang docsjava.util docs

lect05b
arithmetic
and, bad arithmetic

Discuss: hw03b test cases for max, median.

Last time, we saw boolean operators for (resp.) and, or, not: &&, ||, !. We could then work out, step-by-step,

/* Three local variables -- declare and initialize */
boolean healthy = true;
boolean wealthy = true;
boolean wise = false;

(healthy ||  wealthy) && wise      
 healthy || (wealthy  && wise)

/* Same expression but w/o parentheses */
healthy || wealthy && wise
What happens in the last case? This is actually reminiscent of 3+4*5 — where arithmetic (and Java) have a special rule: do all the multiplications-and-divisions (left-to-right), then go back and do all the additions-and-subtractions (left-to-right).

Add explicit parentheses to (part of) the following if condition, without changing the meaning:

/** @return a message to stick in a fortune cookie
 */
String fortuneCookieMessage() {
  int cholesterol = 160;
  double netWorth = 23456.78;
  boolean startHomeworksEarly = true;
  
  if ((cholesterol < 200) && (networth > 1000000) || startHomeworksEarly) {
    return "You are happy.";
    }
  else {
    return "Life is bleak.";
    }
  }

Arithmetic


Review

(Optional) An application of %: public key cryptography

Web traffic is sent on postcards. How to securely communicate your credit-card number to amazon, without any pre-arrangement? “Inconceivable!”?

Amazon might say on their web page:

Our public key pubKey = 37. If you want to send us a secret message privMsg (a two-digit number), multiply your secret number by our public key, and tell us the last two digits (only) of the result: That is, tell us (privMsg * pubKey) % 100. (We can name this result pubMsg.)
Is announcing pubMsg secure, even if there are eavesdroppers? Let's try it! A volunteer: Choose your secret privMsg and write it down, without telling anybody. Compute pubMsg, and announce it. Can any of you eavesdroppers figure out the original message? (You want to just divide by 37, but how to do that in this world of mod-100 arithemetic?) The original privMsg was …

Note that this used no pre-arrangement between the sender and the receiver. This is called “public key cryptography”, since eavesdroppers know as much about breaking the code as the sender.

You could break this code, if you could divide by 37 mod 100. (Or more precisely: find the multiplicative inverse of 37, mod 100.) Project: read about the extended Euclidean algorithm for calculating muliplicative inverses. Break this code!

Although this particular scheme is easy to break with a bit of math knowledge (this Extended Euclidean algorithm), the example is to motivate how a public-key system is even conceivable.

Arithmetic errors

Edict of Programming: When possible, using int is preferred to double. For instance, the price of an item is often best given in integer cents, rather than double dollars. This will avoid accumulation of small errors, as in 2.00-1.10 vs. 200-110.
(We won't enforce this in grading for this class though.)

Example

Exercise for the reader: Write the following, using / and %:

/** Return a nicely formatted String representing a price in dollars.
 * @param cents An amount of money (in cents).
 * @return A String representing cents, in dollars.
 * Examples:
 *   dollarAmount(167) = "1 dollar and 67 cents"
 *   dollarAmount(43) = "0 dollars and 43 cents"
 *   dollarAmount(__) = ______
 */
static String dollarAmount( int cents ) {
  ________________
  }
Hint: % and its complement, integer-division /, are your friends.

Note that really, we're relying on the fact that when Java sees + with a String on one side and an int on the other, then it is calling (behind our back) an int-to-String conversion function.

Comparing doubles

Beware numerical inaccuracies: (2.0 - 1.1 == 0.9), or ( (7.0/25.0)*25.0 == 7.0 ).

double x = 2.0 - 1.1;
double y = 0.9;

x == y
// huh?  That's an unexpected answer.  How to debug?

x
// Oh, now it's clear what happened.
Edict of Programming: Do not use == with doubles.
So how do we see if two doubles are practically-equal? One immediate imponderable is “how close is close enough to be considered practically equal”? Well, for the moment4, let's say being within 0.0003 is close enough: ((y-0.0003 < x) && (x < y+0.0003)) is a start. This amount 0.0003 is often called the “tolerance” of the comparison.

It's likely that your code might have many different places where it wants to compare two doubles within the given tolerance. Rather than repeat something like ((y-0.0003 < x) && (x < y+0.0003)) is a start. many many times, what would we do?
Yes -- write your own helper function to avoid repeated code! So you might write double approxEqual(double a, double b).

Actually, we should look at an relative difference between two terms, rather than an absolute difference.

Review

We have covered many topics over the last 4 weeks:


1Well, they do, but they're not static, and they require new which we haven't talked about yet. And anyway, the built-in conversion functions are tedious to write: (new Integer( numPizzas )).doubleValue().      

2 Well, we haven't talked about classes yet, but Java also lets you cast one class to another (not just numbers). However, casting classes is poor style; it indicates your program isn't correctly mirroring your real-world problem.      

3 This is a preview: Just as there are built-in classes String and Math, there is also a class named Integer. The class Integer is a “wrapper class” for its little cousin, type int. We won't go into details, but just keep in mind that while int and class Integer are related, the primitive type int is not a class.      

4We'll later realize that we really should compare the relative size of the two numbers: 0.001 might be good for comparing people's height in inches, but not for the width of two hairs in inches.      

homeinfolectslabsexamshws
tutor/PIsbreeze (snow day)
Object120 + its docsjava.lang docsjava.util docs


©2012, Ian Barland, Radford University
Last modified 2012.Oct.03 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme