Section 5d

Floating Point Arithmetic


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Working with Decimals

Next steps. The use of mathematical or arithmetic operations with floating point values in most programming languages really is easy. The computer will give you pretty much everything you would expect your calculator to give you. Nevertheless, this brief topic will discuss the use of floating point values, which as discussed in previous topics, is implemented with double data types.

The mathematical operations are the same, as are the results. Consider the following.

double avgHomeCost = 272900.29;
double avgPaid = 454320.46;
double avgMonthlyPayment = 1262.12;
double avgHomePurchaseYears = 22.75;
double interestPaid = avgPaid – avgHomeCost;
double annualPayment = avgMonthlyPayment * 12;
double paidToCostRatio = avgPaid / avgHomeCost;

Some mathematical operations can get more complicated. Consider the following.

int lemonadeDrinkers = 5;
int numberOfColaDrinkers = 3;
double priceOfLemonade = 3.99;
double priceOfCola = 2.99;
double totalDrinkPrice;
totalDrinkPrice = LemonadeDrinkers * priceOfLemonade +
numberOfColaDrinkers * priceOfCola;

First, note that integer and double operations are combined here. There is no significant impact of this for this particular situation, but the process will be discussed in a later topic.

Next, take a look at the syntax. The last operation shows the mathematical expression continuing on to a second line. This is no problem since as you remember, each Java statement is ended with a semicolon. If a line of code happens to go on to a second line, the compiler will not care. On the other hand if you forget the semicolon, or incorrectly place it, that is another matter . . .

There are two considerations here: If you find an expression is long or complicated, you may consider extending it on to another line for clarity; however, if you have a cumbersome mathematical expression, you would probably be better served to break it down into smaller modules, making it more readable and less susceptible to error.

As mentioned, this topic was built to be brief because the floating point math is very aligned with the kinds of math you commonly do every day. The next topic on character math is a little unusual, but it offers some tools you may be able to use at a point in the future.