Chapter 12 - continuationBinary representations
Before spring break we had just started into Chapter 12 "Calculations" in your text and we had just started talking about the bit pattern representation of an integer inside the computer. For example the number 73 looks like 01001001 which represents 64+8+1. We had also spoken briefly about how negative numbers are stored. They are stored as the "two’s complement" of a number. To get the two’s complement of a number you do two things, first change every bit and then add a 1. For the 73 we mentioned above, the procedure would look like this:+73 = 01001001
flip = 10110110
add 1 = 10110111 = -73To make sure we did this correctly we could add our binary representations of +73 and -73 and hopefully come out with zero. Remember that we are dealing with base 2 arithmetic, so that a 1 + 1 = 10 (the binary representation of a 2). Also note that when you are adding columns, every time you get a 1+1=10 or a 1+1+1=11, you need to carry the extra one to the next column. OK, let’s give it a try.0 1 0 0 1 0 0 1
1 0 1 1 0 1 1 1
------------------
1 0 0 0 0 0 0 0 0Now this doesn’t look exactly like a zero since there is an extra 1 over on the left. But we are dealing with only a byte here (eight bits) and there are zeroes in all of the eight bits we started with. Basically the computer throws away that extra 1 and leaves 8 zeroes. Voila! We have exactly what we wanted.Operator precedence (priority)In programming it is important to remember that all operators have a priority (some get done before others). We talked about this a little when we spoke about evaluating boolean expressions, so we won’t say much here. Just remember that the operators "*", "/" and "%" get done before the "+" or "-" and the calculations are done from left-to-right. Here is an example:Library mathematical functions1 + 2 * 3 + 4 / 5 - 6 * 7 + 8
= 1 + 6 + 4 / 5 - 6 * 7 + 8
= 1 + 6 + 0 - 6 * 7 + 8
= 1 + 6 + 0 - 42 + 8
= 7 + 0 - 42 + 8
= 7 - 42 + 8
= -35 + 8
= -27When you are doing a lot of calculations for science or business, you need many things like trig functions and power functions. Java provides a lot of these for you in the Math class. Here are a few:Mathematical Iterationcos(x) cosine
sin(x) sine
tan(x) tangent
abs(x) absolute value
min(x,y) smallest
max(x,y) largest
round(x) rounds a float to nearest integer
log(x) natural log (NOT log base 10)
random() get a random number
sqrt(x) square root
pow(x, y) calculates the power xyUse these like this
hypotenuse = Math.sqrt( pow (x, 2.0) + pow (y, 2.0) );Many math calculations involve what’s called an iteration, where you have to keep adding terms over and over again until a desired "end" point is reached. For example suppose you wanted to find out what the value of the following expression is:1/1 + 1/4 + 1/9 + 1/16 + 1/25 + ....
As you can see this sum could go on forever, but obviously the computer cannot. To estimate this sum, you could add terms (using a loop) until some desired condition is met. Note that the terms in the above series are just 1 divided by the squares of 1, 2, 3, 4, 5, etc. Also suppose that we are not interested in any term that is less than 0.000000001f, which is pretty small. So we could write a loop to calculate this as follows:
answer = 0.0f;
term = 1.0f;
count = 1;
while (term >=0.000000001f) {
answer = answer + term;
count++;
term = 1.0f/pow(count,2.0);
}Note here that count is going 2, 3, 4, 5, etc, inside the loop and that the next term is being calculated as 1 / count2. Therefore when this value gets below a 0.000000001, the while loop will stop. This will not tell us exactly what the infinite series above would be, but it will give us a vary close approximation. (Note: should we use floats here, as indicated in the code above, or should we use doubles?)Mixing data types and castingAs I stated in class, Java does not like to mix data types. Sometimes when you do this the compiler, javac, will give you an error; other times it will just give you a warning. The types of integers and reals have a priority as well. Here it is:Moneydouble <-- highest priorityIf you mix data types, the rule is that the resultant value will be of the higher data type. So if you have
float
long
int
short
byte <--- lowest priorityfloat x;then
int a;
byte r;a + r will result in an "int" type of dataYou can also use what’s called "casting" when dealing with data types. Think about actors on a movie. They are "cast" as a character. In other words, they look and act like someone else when they are on stage. Something similar happens in programming. You can make a data type look and act like another data type for a brief period of time. Suppose you hadx + a will result in a "float" type of data
float x;If you tried to do
int num;x = num;the compiler would flag this as an error. So what you may want to do is make num "act" as a float for just a little while. Do this:x = (float) num;The "cast" type is put in parentheses before the data item. Note that this DOES NOT make num into a float. It only says that num should act as a float for that one line of code.No, I am not going to give you any money but we need to talk about how to make Java print dollars and cents. The problem here is that Java has no direct way in which you could tell it to print a number with just so many decimal values. For example, if you had a value of PI which is, say, 3.14159, and you only wanted to print three decimal positions so that it would look like 3.142, you can’t do it very nicely. The same is true with money. Suppose you did the SavingsAccount problem and you added interest to some money that was in the account and that your final total amount came out to be 127.2341. Well, it would not be nice to display this on an ATM machine. We need plain old dollars and cents. So how to we do it?Graphs:Step one: Get the dollar amount.
Here we can use our casting trick from before. Suppose that the 127.2341 is stored in a float data item called newAmount. Then we can do the following:Step two: Get the cents amount.dollars = (int) newAmount;
Here dollars is an integer item and we are simply telling Java to treat the float amount as an integer for awhile. This actually truncates the float number so that dollars will have a 127 in it.
If we take our original money in newAmount and subtract from it the dollars we just calculated, then we’ll have the cents part. But we need to make sure that the cents is rounded to only two decimal places and we also need to put the cents into an integer as well. How do we do that? Consider the following code:WHEW!cents = Math.round(100.0*(newAmount - dollars));
We are indeed mixing a lot of data types here, but the basic technique is correct. Take the 127.2341, subtract 127 from it to get 0.2341, multiply that by 100 to get 23.41, round that to the nearest integer to get 23 and then store the 23 into the variable called cents.
If we did everything correctly, we should have dollars and cents in integer form now and we can write.
g.drawString( "The amount is $"+ dollars + "." + cents, 50, 50);Note: Your textbook uses an output likeg.drawString ("You money is " + dollars " and " + cents +This is a ok way of doing it, but it doesn’t give the nice format of $127.23 that we’re used to. Actually my way of doing it doesn’t either. CAN YOU SEE WHY? So there are still problems!!!!!
" cents",50,50);Your textbook has a section on Graphs, in other words how do you draw a graph of a function. Look at the example on page 217 in your text. They are trying to draw a graph of a general cubic equation that looks likey = a x3 + b x2 + c x + d
I am not going to go over the code to do this. Most of it you should be able to understand it by now, although it is a bit long and complicated, except you may not understand the part about "scaling". Don’t worry about that either, but I do want you to get some practice with it, which is why you should look at your next assignment posted on the course page.
That is the end of what we will cover in this chapter:
text is Java for Students, by Bell and Parr.