Mathematical Functions - cont
Let’s try out an example now in order to make sure that we know how to use the contents of the Math class.
Type out the following program, which will calculate the radius of a circle in feet and inches, given that it has an area of 100 square feet.
public class MathCalculation{
public static void main(String[ ] args){
double radius = 0.0;
double circleArea = 100.0;
int feet = 0; int inches = 0;
radius = Math.sqrt(circleArea/Math.PI);
// Get the feet as a whole number
feet = (int)Math.floor(radius);
// Calculate the number of inches
inches = (int)Math.round(12.0 * (radius – feet));
System.out.println(“The radius of a circle with area “ + circleArea + “ square feet is\n” + feet + “ feet “ + inches + “ inches”);
}
}
Save the program as MathCalculation.java, compile and run it. You should get the following output:
The radius of a circle with area 100 square feet is
5 feet 8 inches
The first calculation we need, after defining the variables uses the sqrt( ) method to calculate the radius.
Since the area of a circle, with radius r, is given by the formula pir², the radius must be sqrt(area/pi), and we specify the argument to the sqrt( ) method as the expression circleArea/Math.PI. The result is in feet as double value. To get the number of the whole feet we use the floor( ) method. Note that cast to int is necessary, otherwise you will get an error from the compiler.
Lastly we get the number of inches by subtracting the value of whole feet from the original radius, multiplying the fraction of foot by 12 to get the equivalent inches, and then rounding the result to the nearest integer using the round( ) method.
Note how we output the result. We did encounter the System.out.println in our “Hello World” application, but we didn’t explain exactly how it works, so let’s do it now. System is the name of a standard class that contains variables and methods for supporting simple keyboard input and character output to the display. It is contained in the package java.lang so it is always accessible just by using the simple class name, System.
The object out represents the standard output stream – your display screen, and is data member of the class System. This member is referenced by using the class name System separated from the member name out by a period – System.out . The bit at the rightmost end, println(…. ), calls the println( ) method of the object out. This method outputs the text string that appears between the parentheses to your display.
You might be wondering what is the + operator doing here, it’s not arithmetic we are doing, is it? No, but the plus has a special effect when used with character strings: it joins them together (concatenation). Neither circleArea, feet or inches are of type String, but they are all converted to a character string to be compatible with “The radius of a circle with area “.
Exercise 3 – 6 Using math functions
Create an application that gets a random number between 0 and 1000, finds the square root of the number, the log of the number, the sin, cos, and tan of the number and prints them (with suitable text) to the screen. To generate the random number, use the Random class in the java.util package. If your not sure of how these are generated, look up this class and it’s methods in the online documentation.
Tuesday, 21 August 2007
Monday, 20 August 2007
Operators and Assignments (Part 13)
Mathematical Functions
Sooner or later you are likely to need mathematical functions in your programs, even if it’s only obtaining an absolute value or calculating a square root. Java provides a range of methods that support such functions as part of the standard library stored in the package java.lang, all these are available in your program automatically.
The methods that support various additional mathematical functions are implemented in the class Math, so to reference a particular method you need to write Math and a period in front of the method name. For example, to use sqrt( ) which calculates the square root of whatever you place between parentheses, you should write Math.sqrt(aNumber).
The class Math includes a range of numerical functions. Some of the important ones are listed below in the table:
Method Function
abs(arg) Calculates absolute value of the argument
max(arg1, arg2) Returns the larger of the two argument
min(arg1, arg2) Returns the smaller of the two arguments
ceil(arg) Returns the smallest integer that is greater than or equal to the argument
floor(arg) Returns the largest integer that is less than or equal to the argument
round(arg) Calculates the nearest integer to the argument value
The mathematical functions available in the class Math are:
Method Function
sqrt(arg) Calculates the square root of the argument
pow(arg1, arg2) Calculates the first argument raised to the power of the second argument
exp(arg) Calculates e raised to the power of the argument
log(arg) Calculates the natural logarithm (base e) of the argument
random( ) Returns a pseudorandom number between 0.0 and 1.0
The Math class also defines double values for e and pi, which you can access as Math.E and Math.PI respectively. To find out more about the Math class and the methods it provides please refer to Java Documentation.
Sooner or later you are likely to need mathematical functions in your programs, even if it’s only obtaining an absolute value or calculating a square root. Java provides a range of methods that support such functions as part of the standard library stored in the package java.lang, all these are available in your program automatically.
The methods that support various additional mathematical functions are implemented in the class Math, so to reference a particular method you need to write Math and a period in front of the method name. For example, to use sqrt( ) which calculates the square root of whatever you place between parentheses, you should write Math.sqrt(aNumber).
The class Math includes a range of numerical functions. Some of the important ones are listed below in the table:
Method Function
abs(arg) Calculates absolute value of the argument
max(arg1, arg2) Returns the larger of the two argument
min(arg1, arg2) Returns the smaller of the two arguments
ceil(arg) Returns the smallest integer that is greater than or equal to the argument
floor(arg) Returns the largest integer that is less than or equal to the argument
round(arg) Calculates the nearest integer to the argument value
The mathematical functions available in the class Math are:
Method Function
sqrt(arg) Calculates the square root of the argument
pow(arg1, arg2) Calculates the first argument raised to the power of the second argument
exp(arg) Calculates e raised to the power of the argument
log(arg) Calculates the natural logarithm (base e) of the argument
random( ) Returns a pseudorandom number between 0.0 and 1.0
The Math class also defines double values for e and pi, which you can access as Math.E and Math.PI respectively. To find out more about the Math class and the methods it provides please refer to Java Documentation.
Sunday, 19 August 2007
Operators and Assignments (Part 12)
Explicit Casting
It might be that the default way of treating the expressions listed above is not what you want. For example, consider the following Code,
double result;
int two = 2, eleven = 11;
result = 5.5 + eleven/two;
the result variable has a value of 10.5 (because the as both eleven and two are ints, the result of the division is rounded to an int). However, if you wanted the term 11/2 to produce the value 5.5 so the overall result would be 11.0, then you can do this using an explicit cast as follows:
result = 5.5 + (double)eleven/two;
This causes the value stored in eleven to be converted to double before the divide operation takes place and the operand two is also converted to double before the divide is executed. Hence the value of result will be 11.0.
This can (and must or compiler will complain) also go the other way where a large datatype is “squeezed” into a smaller datatype. Consider the next example:
long bigValue = 99.98765L;
int squeezedValue = (int)(bigValue);
without the (int) typecast in the second line, the compiler will flag an error. Variables can automatically be promoted to a longer form though without the need of explicit casting.
Consider the sequence of basic types,
byte --> short --> int --> long --> float --> double
an automatic conversion will be made as long as it is upwards through the sequence, that is from left to right. If you want to go in the opposite direction then you must use an explicit cast. Make sure that you don’t lose information when you do so.
It might be that the default way of treating the expressions listed above is not what you want. For example, consider the following Code,
double result;
int two = 2, eleven = 11;
result = 5.5 + eleven/two;
the result variable has a value of 10.5 (because the as both eleven and two are ints, the result of the division is rounded to an int). However, if you wanted the term 11/2 to produce the value 5.5 so the overall result would be 11.0, then you can do this using an explicit cast as follows:
result = 5.5 + (double)eleven/two;
This causes the value stored in eleven to be converted to double before the divide operation takes place and the operand two is also converted to double before the divide is executed. Hence the value of result will be 11.0.
This can (and must or compiler will complain) also go the other way where a large datatype is “squeezed” into a smaller datatype. Consider the next example:
long bigValue = 99.98765L;
int squeezedValue = (int)(bigValue);
without the (int) typecast in the second line, the compiler will flag an error. Variables can automatically be promoted to a longer form though without the need of explicit casting.
Consider the sequence of basic types,
byte --> short --> int --> long --> float --> double
an automatic conversion will be made as long as it is upwards through the sequence, that is from left to right. If you want to go in the opposite direction then you must use an explicit cast. Make sure that you don’t lose information when you do so.
Saturday, 18 August 2007
Operators and Assignments (Part 11)
Strings - cont
Extracting Substrings
The String class includes a method, substring(), that will extract a substring from a string. There are two versions of this. The first one,
public String substring(int beginIndex)
returns a new string that is a substring of this string., the substring begins with the character at the specified index and extends to the end of this string. The second one,
public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. For example,
"smiles".substring(1, 5) returns "mile"
Exercise 3 – 5
For this exercise you are required to segment the following string:
“We Love our Java Course”
and display it as follows:
We
Love
our
Java
Course
You should make use of both indexOf() and substring() methods. Use the online documentation to help with this exercise. Although we won’t cover loops until later in this section, you may need to use a While loop. This has the syntax of :
while (condition is true) {
// CodeText that needs to iterate goes here
}
Extracting Substrings
The String class includes a method, substring(), that will extract a substring from a string. There are two versions of this. The first one,
public String substring(int beginIndex)
returns a new string that is a substring of this string., the substring begins with the character at the specified index and extends to the end of this string. The second one,
public String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. For example,
"smiles".substring(1, 5) returns "mile"
Exercise 3 – 5
For this exercise you are required to segment the following string:
“We Love our Java Course”
and display it as follows:
We
Love
our
Java
Course
You should make use of both indexOf() and substring() methods. Use the online documentation to help with this exercise. Although we won’t cover loops until later in this section, you may need to use a While loop. This has the syntax of :
while (condition is true) {
// CodeText that needs to iterate goes here
}
Friday, 17 August 2007
Operators and Assignments (Part 10)
Strings - cont
Searching for Substrings
There are two methods available in the class String, that will search a string, indexof() and lastIndexOf(). They both have four different versions to provide a range of possibilities.
Method - Description
indexOf(int ch) - Returns the index within this string of the first occurrence of the specified character ch. If the character, ch doesn’t occur, -1 is returned.
indexOf(int ch, int index) - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. If the value of the index is outside the legal limits for the String object, -1 is returned.
indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring str. If it does not occur as a substring, -1 is returned.
indexOf(String str, int index) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If the value of the index is outside the legal limits for the String object, -1 is returned.
lastIndexOf(int ch) - Returns the index within this string of the last occurrence of the specified character. If the character, ch doesn’t occur, -1 is returned.
lastIndexOf(int ch, int index) - Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. If index is negative -1 is returned. If the character does not occur at or before the index then –1 is returned.
lastIndexOf(String str) - Returns the index within this string of the rightmost occurrence of the specified substring. If it does not occur as a substring, -1 is returned.
lastIndexOf(String str, int index) - Returns the index within this string of the last occurrence of the specified substring. The returned index indicates the start of the substring. If it does not occur as a substring starting at index or earlier, -1 is returned.
Searching for Substrings
There are two methods available in the class String, that will search a string, indexof() and lastIndexOf(). They both have four different versions to provide a range of possibilities.
Method - Description
indexOf(int ch) - Returns the index within this string of the first occurrence of the specified character ch. If the character, ch doesn’t occur, -1 is returned.
indexOf(int ch, int index) - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. If the value of the index is outside the legal limits for the String object, -1 is returned.
indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring str. If it does not occur as a substring, -1 is returned.
indexOf(String str, int index) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If the value of the index is outside the legal limits for the String object, -1 is returned.
lastIndexOf(int ch) - Returns the index within this string of the last occurrence of the specified character. If the character, ch doesn’t occur, -1 is returned.
lastIndexOf(int ch, int index) - Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. If index is negative -1 is returned. If the character does not occur at or before the index then –1 is returned.
lastIndexOf(String str) - Returns the index within this string of the rightmost occurrence of the specified substring. If it does not occur as a substring, -1 is returned.
lastIndexOf(String str, int index) - Returns the index within this string of the last occurrence of the specified substring. The returned index indicates the start of the substring. If it does not occur as a substring starting at index or earlier, -1 is returned.
Subscribe to:
Posts (Atom)